当我尝试获取以下数据集中的最大值时遇到问题。
我的表格如下所示:
+--------+------+-------------+----------------+------------+-------+
| 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 |
我希望所有其他列都只有LEG_ID的最大值。因此,我的结果需要如下所示:
+--------+------+-------------+----------------+------------+-------+
| LEG_ID | TAIL | REPORT_NAME | REPORT_ELEMENT | DATE | VALUE |
+--------+------+-------------+----------------+------------+-------+
| 10 | ABC | Report1 | A | 2018-12-17 | 1050 |
| 8 | ABC | Report1 | B | 2018-12-16 | 1022 |
| 9 | XYZ | Report1 | A | 2018-12-16 | 1021 |
| 9 | XYZ | Report1 | B | 2018-12-17 | 1020 |
我以为max LEG_ID和group by可以工作,但是我遇到了问题,因为我需要日期和值,但是由于打印所有结果,所以无法对其进行分组。知道如何解决吗?
我认为可以使用的代码:
SELECT MAX(R.LEG_ID ), R.REPORT_ELEMENT, R.DATE , R.VALUE FROM READING R GROUP BY R.REPORT_ELEMENT, R.DATE, R.VALUE
创建表的完整数据在这里:
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);
insert into READING values (9, "XYZ", "Report1", "B", '2018-12-17', 1020);
insert into READING values (9, "XYZ", "Report1", "A", '2018-12-16', 1021);
insert into READING values (8, "ABC", "Report1", "B", '2018-12-16', 1022);
insert into READING values (7, "XYZ", "Report1", "A", '2018-12-15', 1010);
insert into READING values (6, "ABC", "Report1", "B", '2018-12-15', 1010);
insert into READING values (5, "ABC", "Report1", "A", '2018-12-13', 1001);
insert into READING values (4, "XYZ", "Report1", "B", '2018-12-12', 1001);