小编典典

SQL连接表-每个“上”匹配字段的连接表上有多行合并为一行?

sql

我有两个要从中提取数据的表。这是我所拥有的最小的娱乐:

Select
 Jobs.Job_Number,
 Jobs.Total_Amount,
 Job_Charges.Charge_Code,
 Job_Charges.Charge_Amount
From
 DB.Jobs
Inner Join
 DB.Job_Charges
On
 Jobs.Job_Number = Job_Charges.Job_Number;

因此,发生的事情是我最终要为每个Job_Number的每个不同的Charge_Code和Charge_Amount获取一行。该行上的其他所有内容都相同。是否有可能使它返回更类似的内容:

Job_Number - Total_Amount - Charge_Code[1] - Charge_Amount[1] - Charge_Code[2] - Charge_Amount[2]

等等?

这样,它就为每个职位编号创建了一行,并且每个相关的费用和金额都在同一行上。我一直在阅读W3,但无法确切地说出这是否可行。有什么帮助,谢谢!


阅读 276

收藏
2021-03-08

共1个答案

小编典典

要在固定数量的列上旋转结果集,可以使用row_number()和条件聚合:

select
    job_number, 
    total_amount,
    max(case when rn = 1 then charge_code end) charge_code1,
    max(case when rn = 1 then charge_amount end) charge_amount1,
    max(case when rn = 2 then charge_code end) charge_code2,
    max(case when rn = 2 then charge_amount end) charge_amount2,
    max(case when rn = 3 then charge_code end) charge_code3,
    max(case when rn = 3 then charge_amount end) charge_amount3 
from (
    select
        j.job_number,
        j.total_amount,
        c.charge_code,
        c.charge_amount,
        row_number() over(partition by job_number, total_amount order by c.charge_code) rn
    from DB.Jobs j
    inner join DB.Job_Charges c on j.job_number = c.job_number
) t
group by job_number, total_amount

上面的查询最多可提供3个费用代码和金额等于工作编号(按工作代码排序)。您可以select使用更多max(case...)表达式来扩展子句,以处理更多表达式。

2021-03-08