这可能很简单 - 但我是SQL新手,不知道要使用哪些函数。
我有一个包含以下数据的表:
Costcode CostDescr
_________________________________
4000 Product
4001 Other
4100 Product
4101 Other
5000 Product
5001 Other
5100 Product
5101 Other
我试图让输出看起来像这样:
X Sales Y Sales CostDescr X Purchases Y Purchases
_______________________________________________________________________________
4000 4100 Product 5000 5100
4001 4101 Other 5001 5101
如何从结果中创建此格式?
答案 0 :(得分:2)
使用此查询:
SELECT CASE
WHEN Costcode >= 4000 AND Costcode < 4100 THEN 'X Sales'
WHEN Costcode >= 4100 AND Costcode < 5000 THEN 'Y Sales'
WHEN Costcode >= 5000 AND Costcode < 5100 THEN 'X Purchases'
WHEN Costcode >= 5100 THEN 'Y Purchases'
END As PivotColumn,
SUBSTRING(CostDescr, 1, CHARINDEX(' ', CostDescr, 1) - 1) AS CostType,
Costcode
FROM #Sales
你得到一个表值表达式,可以执行哪个数据透视表。这是使用您提供的示例数据的上述语句的输出:
PivotColumn CostType Costcode
---------------------------------
X Sales Product 4000
X Sales Other 4001
Y Sales Product 4100
Y Sales Other 4101
X Purchases Product 5000
X Purchases Other 5001
Y Purchases Product 5100
Y Purchases Other 5101
因此,以下查询提供了所需的输出:
SELECT CostType, [X Sales] AS [X Sales], [Y Sales] AS [Y Sales],
[X Purchases] AS [X Purchases], [Y Purchases] AS [Y Purchases]
FROM
(SELECT CASE
WHEN Costcode >= 4000 AND Costcode < 4100 THEN 'X Sales'
WHEN Costcode >= 4100 AND Costcode < 5000 THEN 'Y Sales'
WHEN Costcode >= 5000 AND Costcode < 5100 THEN 'X Purchases'
WHEN Costcode >= 5100 THEN 'Y Purchases'
END As PivotColumn,
SUBSTRING(CostDescr, 1, CHARINDEX(' ', CostDescr, 1) - 1) AS CostType,
Costcode
FROM #Sales) s
PIVOT
(
AVG (Costcode)
FOR PivotColumn IN ( [X Sales], [Y Sales], [X Purchases], [Y Purchases] )
) AS pvt
输出:
CostType X Sales Y Sales X Purchases Y Purchases
------------------------------------------------------
Other 4001 4101 5001 5101
Product 4000 4100 5000 5100