日期:2014-05-18  浏览次数:20468 次

一个会者不难的查询统计sql语句?急求
有如下表:
MC         RQ                   FL       JE  

aaa       20070102       t1       10.2
aaa       20070102       t2       8.2
aaa       20070104       t2       9.2
bbb       20070102       t4       10.2
bbb       20070102       t3       8.2
ccc       20070104       t3       9.2
.
.
.
其中FL的值为不超过5个,且固定为t1、t2、t3、t4、t5
求一SQL语句   如何分时间区间查询出如下结果:
MC         t1JE       t2JE       t3JE     t4JE     t5JE
aaa       10.2       17.4       0           0           0
bbb       0             0             17.4     10.2     0
.
.
急求

------解决方案--------------------
说明一点:楼主的所给的原始数据中“ccc 20070104 t3 9.2”有错误,应该把其中的ccc改为bbb!
下面是我的代码:
declare @tab table(MC varchar(50),RQ varchar(50),FL varchar(50),JE decimal(9,1))
insert @tab values( 'aaa ', '20070102 ', 't1 ',10.2)
insert @tab values( 'aaa ', '20070102 ', 't2 ',8.2)
insert @tab values( 'aaa ', '20070104 ', 't2 ',9.2)
insert @tab values( 'bbb ', '20070102 ', 't4 ',10.2)
insert @tab values( 'bbb ', '20070102 ', 't3 ',8.2)
insert @tab values( 'bbb ', '20070104 ', 't3 ',9.2)
select * from @tab


select tt.mc,sum(t1je),sum(t2je),sum(t3je),sum(t4je),sum(t5je)
from (
select MC,
isnull((select je from @tab where mc=a.mc and rq=a.rq and fl=a.fl and a.fl= 't1 '),0) t1JE,
isnull((select je from @tab where mc=a.mc and rq=a.rq and fl=a.fl and a.fl= 't2 '),0) t2JE,
isnull((select je from @tab where mc=a.mc and rq=a.rq and fl=a.fl and a.fl= 't3 '),0) t3JE,
isnull((select je from @tab where mc=a.mc and rq=a.rq and fl=a.fl and a.fl= 't4 '),0) t4JE,
isnull((select je from @tab where mc=a.mc and rq=a.rq and fl=a.fl and a.fl= 't5 '),0) t5JE
from @tab a) tt
group by tt.mc
返回:
MC t1JE t2JE t3JE t4JE t5JE
aaa 10.2 17.4 0 0 0
bbb 0 0 17.4 10.2 0
------解决方案--------------------
CREATE TABLE #T(MC nvarchar(10),RQ nvarchar(20),FL nvarchar(5),JE numeric(20,1))
INSERT INTO #T
SELECT 'aaa ' , '20070102 ' , 't1 ' ,10.2 UNION ALL
SELECT 'aaa ' , '20070102 ' , 't2 ' ,8.2 UNION ALL
SELECT 'aaa ' , '20070104 ' , 't2 ' ,9.2 UNION ALL
SELECT 'bbb ' , '20070102 ' , 't4 ' ,10.2 UNION ALL
SELECT 'bbb ' , '20070102 ' , 't3 ' ,8.2 UNION ALL
SELECT 'ccc ' , '20070104 ' , 't3 ' ,9.2


SELECT MC
,SUM(CASE FL WHEN 't1 ' THEN JE ELSE 0 END) AS t1JE
,SUM(CASE FL WHEN 't2 ' THEN JE ELSE 0 END) AS t2JE
,SUM(CASE FL WHEN 't3 ' THEN JE ELSE 0 END) AS t3JE
,SUM(CASE FL WHEN 't4 ' THEN JE ELSE 0 END) AS t4J