SQL 跨表查询
A表 字段 NO NAME
11111 张三
B表 字段 NO MONEY
11111 1000
11111 500
11111 2000
22222 300
..... ...
C表 字段 NO PRICE TYPE
11111 500 Retail
11111 2000 Retail
..... ... ......
求解,用一条SQL语句查询条件是B.NO=A.NO,C.NO=A.NO,C.TYPE="RETAIL"得出B.MONEY相加,和C.PRICE相加。
结果如下
NO NAME MONEY PRICE
11111 张三 3500 3500
[解决办法]
Create table A表(NO char(8),NAME char(50))
Insert A表
select '11111','张三'
Create table B表(NO char(8),MONEY int)
Insert B表
select '11111','1000' union all
select '11111','500' union all
select '11111','2000' union all
select '22222','300'
Create table C表(NO char(8),PRICE int,TYPE char(8))
Insert C表
select '11111','500','Retail' union all
select '11111','2000','Retail'
select A.*,SUM(C表.PRICE) as PRICE from
(select A表.NO,A表.NAME,SUM(B表.MONEY) as MONEY from A表
inner join B表 on A表.NO =B表.NO group by A表.NO ,A表.NAME) A,C表
where A.NO=C表.NO group by A.NO,A.NAME,A.MONEY