1
我QUERY:使用數據透視與多個列使用總和?
SELECT dept,csedept_name,January,February,March,April,May,June,July,August,September,October,November,December
FROM (SELECT CAST(employeedept AS INT) as dept,
ROUND(AVG(case when rating1>0 THEN CAST(rating1 AS FLOAT) ELSE null END), 2) as q1,
ROUND(AVG(case when rating2>0 THEN CAST(rating2 AS FLOAT) ELSE null END), 2) as q2,
ROUND(AVG(case when rating3>0 THEN CAST(rating3 AS FLOAT) ELSE null END), 2) as q3,
ROUND(AVG(case when rating4>0 THEN CAST(rating4 AS FLOAT) ELSE null END), 2) as q4,
ROUND(AVG(case when rating5>0 THEN CAST(rating5 AS FLOAT) ELSE null END), 2) as q5,
count(*) as 'totalstars',month_cse= datename(month,execoffice_date),YEAR_cse =YEAR(execoffice_date)
FROM CSEReduxResponses
WHERE
execoffice_status = 1
and employeedept =17
group by employeedept,month(execoffice_date),YEAR(execoffice_date),DATENAME(month,execoffice_date)
)
AS r JOIN CSEReduxDepts d
ON d.csedept_id = r.dept and d.csedept_id=17
PIVOT(SUM(q1)
FOR [month_cse] IN (
[January],[February],[March],[April],[May],[June],[July],[August], [September],[October],[November],[December]
)) AS pvt
其中在每個月根據該部門得到的平均值。 在上面的查詢即時獲得'q1'的總和,並顯示該月份和部門的正確數字 ,但它顯示每個月在1行,我只能顯示'q1'時,我想顯示q1-q5 。
我可能會採取長/錯的方式來做到這一點,也許使用樞軸是錯誤的方式去。
有沒有辦法我可以添加q1-q5並在相應的月份上顯示?
我做了一個http://sqlfiddle.com/#!3/05390/1
哇,是的太多 – user3591637
感謝這個解決方案,我最終想要做的是加起來所有可能q1-q5並得到這個平均值,這將是查詢中可能嗎? – user3591637