MySQL-转置表格并仅打印最大值

时间:2018-12-19 11:45:37

标签: mysql

我有下表,我可以获取每个DATE的最大值,但是我想同时转置它。

我得到的桌子是:

+--------+------+-------------+----------------+------------+-------+
| LEG_ID | TAIL | REPORT_NAME | REPORT_ELEMENT | DATE       | VALUE |
+--------+------+-------------+----------------+------------+-------+
|     10 | ABC  | Report1     | A              | 2018-12-17 |  1050 |
|      9 | XYZ  | Report1     | B              | 2018-12-17 |  1020 |
|      9 | XYZ  | Report1     | A              | 2018-12-16 |  1021 |
|      8 | ABC  | Report1     | B              | 2018-12-16 |  1022 |
|      7 | XYZ  | Report1     | A              | 2018-12-15 |  1010 |
|      6 | ABC  | Report1     | B              | 2018-12-15 |  1010 |
|      5 | ABC  | Report1     | A              | 2018-12-13 |  1001 |
|      4 | XYZ  | Report1     | B              | 2018-12-12 |  1001 |
+--------+------+-------------+----------------+------------+-------+

我要获得最大值的sql代码是:

SELECT *
FROM READING WHERE (DATE,TAIL, REPORT_ELEMENT, VALUE) IN
( SELECT MAX(DATE),TAIL, REPORT_ELEMENT, VALUE
FROM READING
GROUP BY TAIL, REPORT_ELEMENT
);

我想要的结果如下:

+---------+----------+----------+-----------+-----------+
|TAIL     | REPORT A | REPORT B | DATE A    | DATE B    |
+---------+----------+----------+-----------+-----------+
|ABC      | 1050     |    1022  |2018-12-17 |2018-12-16 |
|XYZ      | 1021     |    1020  |2018-12-16 |2018-12-17 |
+---------+----------+----------+-----------+-----------+

用于重现我的表的代码:

CREATE TABLE READING
(

LEG_ID int (10),
TAIL char(255),
REPORT_NAME char (255),
REPORT_ELEMENT char(255),
DATE date,
VALUE int (10));

insert into READING values 
(10, "ABC", "Report1", "A", '2018-12-17', 1050),
(9,  "XYZ", "Report1", "B", '2018-12-17', 1020),
(9,  "XYZ", "Report1", "A", '2018-12-16', 1021),
(8,  "ABC", "Report1", "B", '2018-12-16', 1022),
(7,  "XYZ", "Report1", "A", '2018-12-15', 1010),
(6,  "ABC", "Report1", "B", '2018-12-15', 1010),
(5,  "ABC", "Report1", "A", '2018-12-13', 1001),
(4,  "XYZ", "Report1", "B", '2018-12-12', 1001);

1 个答案:

答案 0 :(得分:1)

像这样旋转它:

SELECT 
   TAIL, 
   MAX(CASE WHEN REPORT_ELEMENT = 'A' THEN DATE END) AS DATEA,
   MAX(CASE WHEN REPORT_ELEMENT = 'B' THEN DATE END) AS DATEB,
   MAX(CASE WHEN REPORT_ELEMENT = 'A' THEN VALUE END) AS VALUEA,
   MAX(CASE WHEN REPORT_ELEMENT = 'B' THEN VALUE END) AS VALUEB
FROM READING
GROUP BY TAIL