从多个表中提取数据

时间:2011-01-13 07:45:14

标签: sql

我有2张桌子

表A

INV    AMT   DISC
1001  1500    150
1002  3000    300

表B

INV  DESC        AMT
1001 CHARGES     100
1001 FREIGHT      30
1001 INSURANCE    20
1002 CHARGES     215
1002 FREIGHT      32
1002 INSURANCE    25

对于表B,我在这里使用SQL将行转换为列格式:

SELECT t.inv,
         MAX(CASE WHEN t.description = 'CHARGES' THEN t.amount ELSE NULL END) AS charges,
         MAX(CASE WHEN t.description = 'FREIGHT' THEN t.amount ELSE NULL END) AS freight,
         MAX(CASE WHEN t.description = 'INSURANCE' THEN t.amount ELSE NULL END) AS insurance
    FROM TABLE B
GROUP BY t.inv
ORDER BY t.inv

如何使用SQL将数据组合成这种格式:

INV     AMT   DISC    CHARGES FREIGHT INSURANCE
1001   1500    150      100      30       20
1002   3000    300      215      32       25

感谢。

1 个答案:

答案 0 :(得分:4)

您需要在表A和表B之间进行联接

declare @TableA as table (inv int, amount int, disc int)
declare @TableB as table (inv int, description varchar(50), amount int)

insert into @TableA values (1001, 1500, 105)
insert into @TableA values (1002, 3000, 300)

insert into @TableB values (1001, 'CHARGES', 100)
insert into @TableB values (1001, 'FREIGHT', 30)
insert into @TableB values (1001, 'INSURANCE', 20)
insert into @TableB values (1002, 'CHARGES', 215)
insert into @TableB values (1002, 'FREIGHT', 32)
insert into @TableB values (1002, 'INSURANCE', 25)

select
    A.inv,
    A.amount,
    A.disc,
    B.charges,
    B.freight,
    B.insurance
from @TableA as A
    inner join (
                SELECT t.inv,
                       MAX(CASE WHEN t.description = 'CHARGES' THEN t.amount ELSE NULL END) AS charges,
                       MAX(CASE WHEN t.description = 'FREIGHT' THEN t.amount ELSE NULL END) AS freight,
                       MAX(CASE WHEN t.description = 'INSURANCE' THEN t.amount ELSE NULL END) AS insurance
                FROM @TableB as t
                GROUP BY t.inv) as B
        on A.inv = B.inv
where
    B.charges = 100 and
    A.inv = 1001

输出

Output from query