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
答案 0 :(得分: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