来自Access Pivot查询的SQL Pivot

时间:2015-10-29 14:46:11

标签: sql-server tsql ms-access sql-server-2012 pivot

我有以下需要转换为SQL的Access查询 -

TRANSFORM 
Sum([anaes_downtime]![ANAESENDTIME]-[anaes_downtime]![anaesstarttime])/24/60 AS Expr1

SELECT downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
FROM ANAES_Downtime
INNER JOIN downtime_seq ON ANAES_Downtime.opnumber = downtime_seq.opnumber
WHERE (((ANAES_Downtime.ANAESSTARTTIME) <> 0 )
    AND ((ANAES_Downtime.ANAESENDTIME) <> 0 ))
GROUP BY downtime_seq.THEATRE, downtime_seq.OPSESSION, downtime_seq.OPDATE
PIVOT "d" & [opseq] IN ("d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","d10","d11","d12","d13","d14","d15","d16","d17","d18","d19","d20");

我理解sql pivot的基础知识,但无法成功转换。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我使用CASE声明找到了我的问题的答案 -

SELECT ad.THEATRE, ad.OPSESSION, ad.OPDATE,
   SUM(CASE WHEN opseq = 0
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd0',
   SUM(CASE WHEN opseq = 1
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd1',
   SUM(CASE WHEN opseq = 2
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd2',
   SUM(CASE WHEN opseq = 3
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd3',
   SUM(CASE WHEN opseq = 4
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd4',
   SUM(CASE WHEN opseq = 5
        THEN ad.ANAESENDTIME - ad.anaesstarttime ELSE 0 END) AS 'd5'...    

 ...FROM #ANAES_Downtime ad INNER JOIN #DowntimeSeq ds ON ad.opnumber = ds.opnumber

WHERE ad.ANAESSTARTTIME <> 0 AND  ad.ANAESENDTIME <> 0
GROUP BY ad.THEATRE, ad.OPSESSION, ad.OPDATE
ORDER BY ad.THEATRE, ad.OPSESSION, ad.OPDATE