2013-08-07 141 views
-1
SELECT * 
FROM 
    (SELECT 
     datename(month, [date]) as [Month], 
     planttype, 
     (sum(noof50kgsbags * 50))[Total Kgs] 
    FROM 
     K_FP_Indent 
    WHERE 
     (date BETWEEN '2013-04-01 00:00.000' AND getdate()) 
     AND (attrited = 'True') 
    GROUP BY 
     datename(month, [date]), month([date]), planttype,[date]) as s 
PIVOT 
(
    SUM([Total Kgs]) 
    FOR [planttype] IN (A,B,C,D) 
) AS s2 

如何使用order by語句查詢此查詢?我知道,我們不能爲嵌入式查詢使用數據透視表排序

輸出使用命令:

Month A  B   C  D 
April x  X   X  X 
August X  X   X  X 
July X  X   X  X 

期望中的OP

Month A  B   C  D 
April x  X   X  X 
July X  X   X  X 
August X  X   X  X 

回答

1

嘗試這一個 -

查詢:

DECLARE @temp TABLE 
(
     planttype CHAR(1) 
    , [Date] DATETIME 
    , noof50kgsbags FLOAT 
    , attrited VARCHAR(5) 
) 

INSERT INTO @temp (planttype, [Date], noof50kgsbags, attrited) 
VALUES 
    ('a', '20130401', 5, 'True'), 
    ('b', '20130801', 5, 'True'), 
    ('c', '20130701', 7, 'True') 

SELECT s2.[Month], a, b, c, d 
FROM 
(
    SELECT 
      [Month] = DATENAME(MONTH, [Date]) 
     , mt = MONTH([Date]) 
     , planttype 
     , [Total Kgs] = SUM(noof50kgsbags * 50) 
    FROM @temp 
    WHERE [Date] BETWEEN '2013-04-01 00:00.000' AND GETDATE() 
     AND attrited = 'True' 
    GROUP BY 
      DATENAME(MONTH, [Date]) 
     , MONTH([Date]) 
     , planttype 
) s 
PIVOT 
(
    SUM([Total Kgs]) 
    FOR [planttype] IN (a, b, c, D) 
) s2 
ORDER BY mt 

輸出:

Month  a  b  c  d 
--------- ------ ------- ------- ------- 
April  250 NULL NULL NULL 
July  NULL NULL 350  NULL 
August NULL 250  NULL NULL 

更新:如何使用以便通過子句嵌入式查詢

SELECT * 
FROM 
(
    SELECT TOP (100) PERCENT --<-- 
      [Month] = DATENAME(MONTH, [Date]) 
     , planttype 
     , [Total Kgs] = SUM(noof50kgsbags * 50) 
    FROM @temp 
    WHERE [Date] BETWEEN '2013-04-01 00:00.000' AND GETDATE() 
     AND attrited = 'True' 
    GROUP BY 
      DATENAME(MONTH, [Date]) 
     , MONTH([Date]) 
     , planttype 
    ORDER BY MONTH([Date]) 
) s 
PIVOT 
(
    SUM([Total Kgs]) 
    FOR [planttype] IN (a, b, c, D) 
) s2 
+0

它顯示瞭如「多部分標識符的錯誤「月亮」不能被束縛。「 – Bhagavan

+0

請給我幾分鐘時間:) – Devart

+1

@ ajmalmhd04 - 'ORDER BY子句在視圖,內聯函數,派生表,子查詢和公用表表達式中無效,除非還指定了TOP,OFFSET或FOR XML。' – Devart