-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 ステートメントを使用するにはどうすればよいですか? インライン クエリに 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
4

1 に答える 1

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

更新: order by 句を使用してクエリをインライン化するにはどうすればよいですか

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
于 2013-08-07T05:50:38.150 に答える