目标 1:您的销售数据存储在 Purchases 表中。您的销售人员希望以透视的形式查看按季度细分的销售数据。
如果您的 Purchases 表没有销售数据,请创建一些。确保数据跨越四个季度。接下来,编写一个查询来透视数据,如下所示:
Album Q1 Q2 Q3 Q4
OK Computer 2 5 3 7
Sea Change 8 6 2 1
不要创建单独的表或视图。不要更改任何表格。
将您的查询保存为 dba1lesson10project1.sql 并提交项目。
这是我需要做的。但是,它希望我使用的表看起来像这样。它在作业中指出我根本无法更改它。
CustomerID DateOfPurchase SongID
1 2007-03-31 3
3 2007-06-30 4
4 2007-09-30 4
5 2007-12-31 5
我努力了
SELECT SongID,
SUM(CASE WHEN DateOfPurchase = '2007-03-31' THEN DateOfPurchase ElSE 0 END) AS 'Q1',
SUM(CASE WHEN DateOfPurchase = '2007-06-30' THEN DateOfPurchase ELSE 0 END) AS 'Q2',
SUM(CASE WHEN DateOfPurchase = '2007-09-30' THEN DateOfPurchase ELSE 0 END) AS 'Q3',
SUM(CASE WHEN DateOfPurchase = '2007-12-31' THEN DateOfPurchase ELSE 0 END) AS 'Q4'
FROM Purchases
GROUP BY SongID;
连同其他变体:
SELECT SongID,
SUM(CASE WHEN DateOfPurchase = '2007-03-31' THEN CustomerID ElSE 0 END) AS 'Q1',
SUM(CASE WHEN DateOfPurchase = '2007-06-30' THEN CustomerID ELSE 0 END) AS 'Q2',
SUM(CASE WHEN DateOfPurchase = '2007-09-30' THEN CustomerID ELSE 0 END) AS 'Q3',
SUM(CASE WHEN DateOfPurchase = '2007-12-31' THEN CustomerID ELSE 0 END) AS 'Q4'
FROM Purchases
GROUP BY SongID;
和:
SELECT SongID,
SUM(CASE WHEN DateOfPurchase = '2007-03-31' THEN SongID ElSE 0 END) AS 'Q1',
SUM(CASE WHEN DateOfPurchase = '2007-06-30' THEN SongID ELSE 0 END) AS 'Q2',
SUM(CASE WHEN DateOfPurchase = '2007-09-30' THEN SongID ELSE 0 END) AS 'Q3',
SUM(CASE WHEN DateOfPurchase = '2007-12-31' THEN SongID ELSE 0 END) AS 'Q4'
FROM Purchases
GROUP BY SongID;
其中,最后两个几乎可以满足我的需求。但是,每个 SongID 和 Quarter 只有一次购买。他们向我展示了 CustomerID 或 SongID。我对我需要做什么有一个基本的了解。但是由于无法更改表格以显示实际购买了多少,我不知道该怎么做。有什么建议么?