SELECT ProdName, Sales,
1 AS January, 2 AS February, 3 AS March, 4 AS April, 5 AS May, 6 AS June,
7 AS July, 8 AS August, 9 AS September, 10 AS October,
11 AS November, 12 AS December
FROM
(SELECT actsales as Sales , EXTRACT (month from factdate) as Month, ProdName
FROM factcoffee, prodcoffee
WHERE factcoffee.ProductId = prodcoffee.productid)
PIVOT
(
SUM (Sales)
FOR Month IN
( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 )
);
在第1行中出现Sales的错误。如果仅从第1行中删除销售,则根据需要,我将产品的数据透视表作为行,将月份作为列,但是值不是销售而是一月列仅1个,二月列2个,依此类推。 如果在第1行中执行SELECT *,我将按月获得每种产品的正确销售价值。但是列名称显然不是月份名称,而只是1,2,...
答案 0 :(得分:0)
您的查询很好,但是请尝试使其更具可读性
SELECT ProdName
, Sales
,[1] AS January
,[2] AS February
,[3] AS March
,[4] AS April
,[5] AS May
,[6] AS June
,[7] AS July
,[8] AS August
,[9] AS September
,[10] AS October
,[11] AS November
,[12] AS December
FROM
(SELECT actsales as Sales , EXTRACT (month from factdate) as Month,
ProdName
FROM factcoffee, prodcoffee
WHERE factcoffee.ProductId = prodcoffee.productid)
PIVOT
(
SUM (Sales)
FOR Month IN
( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) as PVT;
不要忘记将数据透视表重命名为PVT或其他名称。有时代码会因为这样做或忘记括号而失败。
此外,如果您可以尝试使用join代替FROM factcoffee, prodcoffee.
,则更具可读性