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

请问这个查询语句应该怎么写????????
表里记录着四个季度的得分,非总计,是多条记录

列名如下:

UserName --用户名
Scoring --得分
content --得分理由
Quarter --季度(1,2,3,4)


要一个结果

用户名 一季度得分 一季度得分理由 二季度得分 二季度得分理由 三季度得分 三季度得分理由 四季度得分 四季度得分理由 



------解决方案--------------------
SQL code
select t.*. ,t1.一季度得分理由,t1.二季度得分理由,t1.三季度得分理由,t1.四季度得分理由 (select userName,
case when Quarter = 1 then Scoring end 一季度得分,
case when Quarter = 2 then Scoring end 二季度得分,
case when Quarter = 3 then Scoring end 三季度得分,
case when Quarter = 4 then Scoring end 四季度得分
from tb group by userName
) t
left join
(select UserName,
case when Quarter = 1 then content end 一季度得分理由,
case when Quarter = 2 then content end 二季度得分理由,
case when Quarter = 3 then content end 三季度得分理由,
case when Quarter = 4 then content end 四季度得分理由 
from tb group by UserName) t1
on t.UserName  = t1.UserName

------解决方案--------------------
可以参考
http://topic.csdn.net/u/20110926/15/4bceea0a-51a8-4abd-a4e9-230bdfd9a2cc.html
------解决方案--------------------
SELECT UserName
,MAX([一季度]) as '一季度'
,MAX([一季度得分理由]) as '一季度得分理由'
,MAX([二季度]) as '二季度'
,MAX([二季度得分理由]) as '二季度得分理由'
,MAX([三季度]) AS '三季度'
,MAX([三季度得分理由]) as '三季度得分理由'
,MAX([四季度]) AS '四季度'
,MAX([四季度得分理由]) as '四季度得分理由'
FROM (
SELECT UserName 
,CASE Season WHEN 1 THEN Scoring END as '一季度'
,CASE Season WHEN 1 THEN Content END AS '一季度得分理由'
,CASE Season WHEN 2 THEN Scoring END AS '二季度'
,CASE Season WHEN 2 THEN Content END AS '二季度得分理由'
,CASE Season WHEN 3 THEN Scoring END AS '三季度'
,CASE Season WHEN 3 THEN Content END AS '三季度得分理由'
,CASE Season WHEN 4 THEN Scoring END AS '四季度'
,CASE Season WHEN 4 THEN Content END AS '四季度得分理由'
FROM #T
) as tmp
GROUP BY UserName
------解决方案--------------------
SQL code
--你的每个用户其每个季度应该是唯一的吧?
select UserName,
       max(case Quarter when 1 then Scoring else 0 end)  [一季度得分],
       max(case Quarter when 1 then content else '' end) [一季度得分理由],
       max(case Quarter when 2 then Scoring else 0 end)  [二季度得分],
       max(case Quarter when 2 then content else '' end) [二季度得分理由],
       max(case Quarter when 3 then Scoring else 0 end)  [三季度得分],
       max(case Quarter when 3 then content else '' end) [三季度得分理由],
       max(case Quarter when 4 then Scoring else 0 end)  [四季度得分],
       max(case Quarter when 4 then content else '' end) [四季度得分理由]
from tb
group by UserName

--如果你的每个用户其每个季度的记录不唯一?
select UserName,
       sum(case Quarter when 1 then Scoring else 0 end)  [一季度得分],
       max(content) [一季度得分理由],
       sum(case Quarter when 2 then Scoring else 0 end)  [二季度得分],
       max(content) [二季度得分理由],
       sum(case Quarter when 3 then Scoring else 0 end)  [三季度得分],
       max(content) [三季度得分理由],
       sum(case Quarter when 4 then Scoring else 0 end)  [四季度得分],
       max(content) [四季度得分理由]
from tb
group by UserName