需要帮助。
我有这个数据表以供说明。 (还有许多其他行的数据与不同的客户。请在答案中考虑这一点)
RowID Customer Category Date Figure1
1 Cust1 Week 1 Jun-11 10
2 Cust1 Week 2 Jun-11 20
3 Cust1 Week 3 Jun-11 30
4 Cust1 Week 4 Jun-11 40
5 Cust1 Actual Jun-11 200
6 Cust1 Forecast Jun-11 100
7 Cust2 Forecast Jun-11 100
我希望它只显示类别Actual
(第5行),包括透视类别中的RowID
,如下所示
这应该是输出。
RowID Customer Date Week1 Week2 Week3 Week4 Actual Forecast
5 Cust1 Jun-11 10 20 30 40 200 100
任何帮助都将不胜感激。
提前致谢。
尝试过Pivot,但它给了我这不是我想要的。
RowID Customer Date Week1 Week2 Week3 Week4 Actual Forecast
1 Cust1 Jun-11 10 null null null null null
2 Cust1 Jun-11 null 20 null null null null
3 Cust1 Jun-11 null null 30 null null null
4 Cust1 Jun-11 null null null 40 null null
5 Cust1 Jun-11 null null null null 200 null
6 Cust1 Jun-11 null null null null null 100
答案 0 :(得分:1)
PIVOT
没问题,但之后需要GROUP BY
和SUM
。
或者,你可以在所有不同的代码标准上自我加入,但它可以比在一个地方拥有值列表一样可维护性稍差,就像你可以使用PIVOT一样。
答案 1 :(得分:0)
你可以这样做:
SELECT
RowID,
Customer,
Date,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Week 1') AS Week1,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Week 2') AS Week2,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Week 3') AS Week3,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Week 4') AS Week4,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Actual') AS Actual,
(SELECT Figure1 FROM sotest WHERE Customer = 'Cust1' AND Date = 'Jun-11' AND Category = 'Forecast') AS Forecast
FROM
sotest
WHERE
Customer = 'Cust1'
AND Date = 'Jun-11'
AND Category = 'Actual'
在存储过程中包含起来应该相当容易,您可以在其中传递CustomerID和Date参数。
答案 2 :(得分:0)
根据两个参数(@MyCustomer
& @MyDate
)尝试此解决方案:
DECLARE @MyCustomer VARCHAR(10) = 'Cust1'
,@MyDate VARCHAR(10) = 'Jun-11';
SELECT pvt.*
FROM
(
SELECT t.Customer, t.Date, t.Category, t.Figure1
FROM MyTable t
WHERE t.Customer = @MyCustomer AND t.[Date] = @MyDaye
) src
PIVOT ( SUM(src.Figure1) FOR src.Category IN ([Week 1], [Week 2], [Week 3], [Week 4], [Actual], [Forecast]) ) pvt
基本思路是在src
派生表中仅过滤您需要进行数据透视的那些行和列,无论是更多还是更少。