gpt4 book ai didi

mysql - 使用 MySql 旋转数据

转载 作者:行者123 更新时间:2023-11-30 23:13:45 26 4
gpt4 key购买 nike

目标 1:您的销售数据存储在 Purchases 表中。您的销售人员希望以旋转形式查看按季度分割的销售数据。

如果您的 Purchases 表没有销售数据,请创建一些。确保数据跨越四个季度。接下来,编写一个查询来透视数据,如下所示:

Album              Q1   Q2   Q3   Q4

OK Computer 2 5 3 7

Sea Change 8 6 2 1

不要创建单独的表或 View 。不要更改任何表格。

将查询保存为 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。我对我需要做什么有一个基本的了解。但是如果无法更改表格以显示实际购买了多少,我不确定该怎么做。有什么建议吗?

最佳答案

您当前的查询非常接近,我建议进行一些小的更改。您正在对日期进行硬编码,但是如果您在第一季度的日期不等于 2007-03-31 会发生什么,它不会显示。

我会使用 QUARTER() MySQL 中的函数,这将根据日期值返回第 1-4 季度。

其次,我认为您不想对 SongID 求和,在您的 CASE 表达式中我会将 SongID 替换为 1 个类似的到以下内容:

SELECT SongID,
SUM(CASE WHEN Quarter(DateOfPurchase) = 1 THEN 1 ElSE 0 END) AS Q1,
SUM(CASE WHEN Quarter(DateOfPurchase) = 2 THEN 1 ELSE 0 END) AS Q2,
SUM(CASE WHEN Quarter(DateOfPurchase) = 3 THEN 1 ELSE 0 END) AS Q3,
SUM(CASE WHEN Quarter(DateOfPurchase) = 4 THEN 1 ELSE 0 END) AS Q4
FROM Purchases
GROUP BY SongID;

参见 SQL Fiddle with Demo

关于mysql - 使用 MySql 旋转数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18797371/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com