2013-11-04 73 views
3

我剛剛在左外連接處得到了我的頭,我正在練習PIVOTS。左外連接和PIVOT之間是否有一般關係?

我想知道是否有可能將此查詢轉換爲樞軸?

SELECT mydrawercustomer.customerface, 
     mydrawerordertype.ordertypeface, 
     mydrawerorder.LM, 
     Datediff(hour, a1.playdate, a2.playdate) AS [RunningTime1], 
     Datediff(hour, a2.playdate, a3.playdate) AS [RunningTime2], 
     Datediff(hour, a3.playdate, a4.playdate) AS [RunningTime3], 
     Datediff(hour, a1.playdate, a4.playdate) AS [RunningTime4] 
FROM mydrawerorder 
     LEFT OUTER JOIN mydrawercustomer 
        ON mydrawerorder.customerKEY = mydrawercustomer.customerKEY 
     LEFT OUTER JOIN mydrawerorderactivity a1 
        ON mydrawerorder.orderKEY = a1.orderKEY 
         AND a1.activityKEY = 1 
     LEFT OUTER JOIN mydrawerorderactivity a2 
        ON mydrawerorder.orderKEY = a2.orderKEY 
         AND a2.activityKEY = 2 
     LEFT OUTER JOIN mydrawerorderactivity a3 
        ON mydrawerorder.orderKEY = a3.orderKEY 
         AND a3.activityKEY = 3 
     LEFT OUTER JOIN mydrawerorderactivity a4 
        ON mydrawerorder.orderKEY = a4.orderKEY 
         AND a4.activityKEY = 4 
     INNER JOIN mydrawerordertype 
       ON mydrawerorder.ordertypeKEY = mydrawerordertype.ordertypeKEY 
ORDER BY mydrawercustomer.customerface, 
      mydrawerordertype.ordertypeface, 
      mydrawerorder.LM, 
      a1.playdate 

我不要求你解決我的挑戰我,但我只是要求對這種類型的左外連接的查詢轉換成PIVOT入門幫助。

+0

嗨,給看看這個鏈接應該幫助找出如何轉換的查詢http://www.techbubbles.com/sql-server/pivot-unpivot-operators-in-sql-server-2008/ – Raphael

+0

在這種情況下更有用的鏈接將如下:http://technet.microsoft.com /en-us/library/ms177410(v=sql.105).aspx – Sandr

+0

請給我一個數據的例子嗎?(可以在sqlfiddle上) –

回答

3

通常LEFT JOINPIVOT之間的關係不是直接的,但在你的情況下,可以找到解決方案。

您的查詢將看起來如下:根據使用PIVOT

select customerface, ordertypeface, LM, 
    Datediff(hour, [1], [2]) AS [RunningTime1], 
    Datediff(hour, [2], [3]) AS [RunningTime2], 
    Datediff(hour, [3], [4]) AS [RunningTime3], 
    Datediff(hour, [1], [4]) AS [RunningTime4] 
from 
(
    SELECT 
     c.customerface, 
     ot.ordertypeface, 
     o.LM, 
     a.activityKEY, 
     a.playdate, 
     o.orderKEY 
    FROM mydrawerorder o 
    INNER JOIN mydrawerordertype ot 
     ON o.ordertypeKEY = ot.ordertypeKEY 
    LEFT JOIN mydrawercustomer c 
     ON o.customerKEY = c.customerKEY 
    LEFT JOIN mydrawerorderactivity a 
     ON o.orderKEY = a.orderKEY 
     and a.activityKEY in (1, 2, 3, 4) 
) x 
pivot 
(
    max(playdate) 
    for activityKEY in ([1], [2], [3], [4]) 
) as pvt 
ORDER BY customerface, ordertypeface, LM, [1] 

更多信息可以在這裏找到:http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

相關問題