当前位置: 首页 > 面试题库 >

将结果分组到两个表中

唐珂
2023-03-14
问题内容

我有下表。

CREATE TEMPORARY TABLE temp_detail
(
  purchase_order_detail_id INTEGER,
  item_id integer,
  qty numeric(18,2),
  project_id integer,
  category_id integer,
  supplier_id integer,
  rate numeric(18,2)
);

我正在使用ID获取分组结果

  SELECT array_agg(purchase_order_detail_id), project_id, category_id, supplier_id 
  FROM temp_detail 
  GROUP BY project_id, category_id, supplier_id

现在,我想将project_id,category_id,supplier_id插入主表,并将item_id,qty,rate插入其明细表。明细表会将主表ID作为外键。请帮忙。


问题答案:

假设这个模式:

create table master (
    master_id serial primary key,
    project_id int,
    category_id int,
    supplier_id int
);
create table detail (
    detail_id int,
    item_id int,
    qty numeric(18,2),
    rate numeric(18,2),
    master_id int references master (master_id)
);
create temporary table temp_detail (
    purchase_order_detail_id integer,
    item_id integer,
    qty numeric(18,2),
    project_id integer,
    category_id integer,
    supplier_id integer,
    rate numeric(18,2)
);

可以做到这一点:

with d as (
    insert into master (project_id, category_id, supplier_id)
    select distinct project_id, category_id, supplier_id
    from temp_detail
    returning *
)
insert into detail (item_id, qty, rate, master_id)
select item_id, qty, rate, master_id
from
    temp_detail td
    inner join
    d on (td.project_id, td.category_id, td.supplier_id) = (d.project_id, d.category_id, d.supplier_id)
;


 类似资料:
  • 问题内容: 我正在尝试提出一种SQL解决方案,以安排输出以匹配预期的JSON格式。 我有一些简单的SQL来突出显示问题的根源。 它将返回JSON为; 我需要的是在“ telecome”数组中添加额外的对象,使其看起来像; 我错误地认为我可以继续添加到我的SQL中,如下所示: 但是它将按照我的命名缩进嵌套项目; 由于与另一个列名或别名冲突,无法在JSON输出中生成属性’telecom.use’。SE

  • 问题内容: 我正在使用PHP和PDO从数据库检索一组值,然后使用以下代码按第一列进行分组: 这意味着如果我的数据采用以下格式: 它返回为: 我将如何按Column1和Column2分组,这样我会得到以下信息: 可以结合使用PDO常数吗? 谢谢 问题答案: 如您所见,通过将数组与一个指定的列进行分组,可以轻松地轻松重建数组。您需要将二维数组(数据库的结果)转换为三维数组,但是 无法 以这种方式重建它

  • 问题内容: 我有一个查询,该查询获取由last_name排序的所有记录。现在,我想创建一个循环,将这些结果按姓氏的第一个字母分组,并在该组上方显示字母,即 谢谢! 问题答案: 按顺序对结果进行排序,并跟踪第一个字母的变化:

  • 想象我们有两个数组: 获取包含两者相乘值的第三个String数组的更好方法是什么?比如: 我知道,我可以使用循环并将1中的每个元素与2中的每个元素连接起来,并将结果放入3中。但实际上和中的元素要多得多。Java中是否有专门的工具使其更有效?

  • 我在这里拥有的是一组三个数组列表。一个包含姓名、姓氏、uid和学位方案的学生数组列表。然后,我还有一个模块列表,每个模块还包含一个学生ID数组列表,用于在该特定模块上注册的学生。 我要做的是将学生的数组列表与用户ID的数组列表链接起来,这样程序就会查看ID,并将它们与包含所有学生详细信息的列表进行比较,然后编写一份包含完整学生详细信息和他们注册的模块的合并报告。 我的数组列表设置得很好,但是我很难

  • 给定一个< code>n数和sum 的列表,将这些数分成< code >两个组,使得每组中的数之和小于或等于s。如果可以分组,则打印< code>YES,如果不能分组,则打印< code>NO。 例如,如果< code>n=3,s=4和< code>n数是< code>2,4,2。在这种情况下,输出为< code>YES,因为可以形成两个组< code>(2,2)和(4)。 我的解决方案如下。 是