gpt4 book ai didi

MySQL group by 不起作用

转载 作者:行者123 更新时间:2023-11-29 17:09:36 25 4
gpt4 key购买 nike

我有一个名为 nasdaq_transactions 的表,如下所示

Ticker  Close   Date
GOOG 1195.06 08/15/2018
AAPL 215.15 08/15/2018
MSFT 104.56 08/15/2018
GOOG 1198.11 08/16/2018
AAPL 216.1 08/16/2018
MSFT 105.1 08/16/2018
GOOG 1200.96 08/17/2018
AAPL 217.58 08/17/2018
MSFT 107.58 08/17/2018

想要构建一个提供输出的查询

Ticker  08/15/2018  08/16/2018  08/17/2018
GOOG 1196.06 1198.11 1200.96
AAPL 215.15 216.1 217.58
MSFT 104.56 105.1 107.58

编写查询

select tabl.ticker, CASE WHEN tabl.date = '2018-08-15' THEN tabl.close END AS '2018-08-15',CASE WHEN tabl.date = '2018-08-16' THEN tabl.close END AS '2018-08-16', CASE WHEN tabl.date = '2018-08-17' THEN tabl.close END AS '2018-08-15'(select ticker, close, date from nasdaq_transactions where date in ('2018-08-15', '2018-08-16','2018-08-17'))tabl

此查询的部分输出为

+------------+------------+------------+-----------+
| Ticker | 2018-08-15 | 2018-08-16 |2018-08-17 |
+------------+------------+------------+-----------+
| GOOG | 1196.06 | NULL | NULL |
| GOOG | NULL | 1198.11 | NULL |
| GOOG | NULL | NULL | 1200.96 |
| AAPL | 215.15 | NULL | NULL |

不允许分组,以便我可以获得单行代码,我不是数据库专家。感谢有效的修复。

最佳答案

我猜你正在追求这个。请注意,通常最好在应用程序代码中处理数据显示问题...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(ticker CHAR(4) NOT NULL
,close DECIMAL(7,2) NOT NULL
,date DATE NOT NULL
,PRIMARY KEY(ticker,date)
);

INSERT INTO my_table VALUES
('GOOG',1195.06,'2018/08/15'),
('AAPL', 215.15,'2018/08/15'),
('MSFT', 104.56,'2018/08/15'),
('GOOG',1198.11,'2018/08/16'),
('AAPL', 216.1 ,'2018/08/16'),
('MSFT', 105.1 ,'2018/08/16'),
('GOOG',1200.96,'2018/08/17'),
('AAPL', 217.58,'2018/08/17'),
('MSFT', 107.58,'2018/08/17');

SELECT ticker
, MAX(CASE WHEN date = '2018-08-15' THEN close END) '2018-08-15'
, MAX(CASE WHEN date = '2018-08-16' THEN close END) '2018-08-16'
, MAX(CASE WHEN date = '2018-08-17' THEN close END) '2018-08-17'
FROM my_table
GROUP
BY ticker;

+--------+------------+------------+------------+
| ticker | 2018-08-15 | 2018-08-16 | 2018-08-17 |
+--------+------------+------------+------------+
| AAPL | 215.15 | 216.10 | 217.58 |
| GOOG | 1195.06 | 1198.11 | 1200.96 |
| MSFT | 104.56 | 105.10 | 107.58 |
+--------+------------+------------+------------+

关于MySQL group by 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51931678/

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