MySQL group by不起作用

时间:2018-08-20 13:21:08

标签: mysql

我有一个名为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    |

不允许分组依据,这样我就可以获得一行股票,不是数据库专家。赞赏有效的修复程序。

2 个答案:

答案 0 :(得分:0)

我想你是在这之后。请注意,通常最好处理应用程序代码中的数据显示问题...

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 |
+--------+------------+------------+------------+

答案 1 :(得分:0)

使用group by应该完美

select tabl.ticker,
 Max(CASE WHEN tabl.date = '2018-08-15' THEN tabl.close END AS '2018-08-15'),
 Max(CASE WHEN tabl.date = '2018-08-16' THEN tabl.close END AS '2018-08-16'),
 Max(CASE WHEN tabl.date = '2018-08-17' THEN tabl.close END AS '2018-08-15'),
from tabl
group by ticker;