来自不同表的查询

时间:2011-01-27 03:49:11

标签: sql sql-server database

我有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

为了组合两个表,我使用了以下查询(由Mikael Eriksson给出): -

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    

然后,我将得到以下输出: -

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

问题,如果我想说的话,我怎么能在前面的语句中添加一个查询,其中费用等于100.最终结果如下: -

INV     AMT   DISC    CHARGES FREIGHT INSURANCE
1001   1500    150      100      30       20

1 个答案:

答案 0 :(得分:4)

select
    A.inv,
    A.amt,
    A.disc,
    B.charges,
    B.freight,
    B.insurance
from TableA as A
    inner join (
                SELECT t.inv,
                       MAX(CASE WHEN t.descr = 'CHARGES' THEN t.amt ELSE NULL END) AS charges,
                       MAX(CASE WHEN t.descr = 'FREIGHT' THEN t.amt ELSE NULL END) AS freight,
                       MAX(CASE WHEN t.descr = 'INSURANCE' THEN t.amt ELSE NULL END) AS insurance
                FROM TableB as t
                GROUP BY t.inv) as B
        on A.inv = B.inv
where charges = 100   --<< just add this

根据包含tableb.amt = 100 and descr = 'charges'的行数,您最好以这种方式编写查询。

select a.inv, a.amt, a.disc,
  b.amt AS charges,
  c.amt AS freight,
  d.amt AS insurance
from tablea a
inner join tableb b on b.inv = a.inv and b.descr = 'CHARGES' and b.amt = 100
left join tableb c on c.inv = a.inv and c.descr = 'FREIGHT'
left join tableb d on d.inv = a.inv and d.descr = 'INSURANCE'

测试数据

create table tablea (inv int, amt int, disc int);
insert tablea select 1001,1500,150;
insert tablea select 1002,3000,300;

create table tableb (inv int, descr varchar(10), amt int);
insert tableb select 1001, 'CHARGES', 100;
insert tableb select 1001, 'FREIGHT', 30;
insert tableb select 1001, 'INSURANCE', 20;
insert tableb select 1002, 'CHARGES', 215;
insert tableb select 1002, 'FREIGHT', 32;
insert tableb select 1002, 'INSURANCE', 25;

输出

inv         amt         disc        charges     freight     insurance
----------- ----------- ----------- ----------- ----------- -----------
1001        1500        150         100         30          20
Warning: Null value is eliminated by an aggregate or other SET operation.

(1 row(s) affected)

注意:使用建议的第二个查询,输出中不存在警告