进行多表查询的时候,需要达到这样的效果。
表user
用户名 电话号码 联系方式...
表pay
电话号码 月份 付费
6777777 10 100
6777777 11 120
6775555 10 100
6775555 11 120
如要查询11月费用,查询后得到
用户名 电话号码 10月付费 11月付费
6777777 100 120
6775555 100 120
怎样才能达到这样得效果啊!!
用一个临时表实现
测试:
create table t1(用户名 char(10),电话号码 char(7))
insert t1 values(abc,6777777)
insert t1 values(def,6775555)
create table pay(电话号码 char(7),月份 int,付费 int)
insert pay select 6777777,10,100
union all select 6777777,11,120
union all select 6775555,10,100
union all select 6775555,11,120
select a.用户名,b.电话号码,
sum(case when 月份=10 then 付费 else 0 end) as [10月付费],
sum(case when 月份=11 then 付费 else 0 end) as [11月付费]
from t1 a
join pay b on a.电话号码 = b.电话号码
group by a.用户名,b.电话号码
order by b.电话号码 desc
/* 结果
用户名 电话号码 10月付费 11月付费
---------- ------- ----------- -----------
abc 6777777 100 120
def 6775555 100 120
*/
txlicenhe(马可)的方法完全可行,以前也做过的,就是一个组织数据的过程,只是如果用oracle数据库的话,case..then..要改成DECODE的