更新:
表:mydata
id trans_id CURRENT CUST_DATE
------------------------------------
16 2362 152.40 2015-05-11
16 2363 146.80 2015-05-26
16 1669 147.00 2015-06-16
16 1979 148.60 2015-07-06
16 2344 144.00 2015-08-06
104 1280 161.40 2015-05-29
104 1553 158.20 2015-06-10
104 1898 158.20 2015-06-29
104 2131 158.20 2015-07-15
104 2223 158.20 2015-07-27
104 2294 158.20 2015-08-03
我需要一个查询,它将根据CUST_DATE在每组ID中返回CURRENT的第一个和最后一个值。
要指出的一些项目:
我已经用这个看似简单的查询了两天了......只是无法绕过它。
预期产出(扁平结构):
id CURRENT_MAX CURRENT_MIN
-------------------------------
16 152.40 144.00
104 161.40 158.20
答案 0 :(得分:0)
几行共享相同的最小电流,所以我假设你想要所有这些,因为你没有另外指定......
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL
, trans_id INT NOT NULL
,CURRENT DECIMAL(5,2)
,CUST_DATE DATE NOT NULL
);
INSERT INTO my_table VALUES
(16 ,2362 ,152.40 ,'2015-05-11'),
(16 ,2363 ,146.80 ,'2015-05-26'),
(16 ,1669 ,147.00 ,'2015-06-16'),
(16 ,1979 ,148.60 ,'2015-07-06'),
(16 ,2344 ,144.00 ,'2015-08-06'),
(104 ,1280 ,161.40 ,'2015-05-29'),
(104 ,1553 ,158.20 ,'2015-06-10'),
(104 ,1898 ,158.20 ,'2015-06-29'),
(104 ,2131 ,158.20 ,'2015-07-15'),
(104 ,2223 ,158.20 ,'2015-07-27'),
(104 ,2294 ,158.20 ,'2015-08-03');
SELECT a.*
FROM my_table a
JOIN
(
SELECT id, MAX(current) x_current FROM my_table GROUP BY id
UNION
SELECT id, MIN(current) x_current FROM my_table GROUP BY id
) b
ON b.id = a.id AND b.x_current = a.current;
+-----+----------+---------+------------+
| id | trans_id | CURRENT | CUST_DATE |
+-----+----------+---------+------------+
| 16 | 2362 | 152.40 | 2015-05-11 |
| 16 | 2344 | 144.00 | 2015-08-06 |
| 104 | 1280 | 161.40 | 2015-05-29 |
| 104 | 1553 | 158.20 | 2015-06-10 |
| 104 | 1898 | 158.20 | 2015-06-29 |
| 104 | 2131 | 158.20 | 2015-07-15 |
| 104 | 2223 | 158.20 | 2015-07-27 |
| 104 | 2294 | 158.20 | 2015-08-03 |
+-----+----------+---------+------------+
或
SELECT a.*
FROM my_table a
JOIN
(
SELECT id
, MAX(current) max_current
, MIN(current) min_current
FROM my_table
GROUP
BY id
) b
ON b.id = a.id AND a.current IN (b.max_current,b.min_current);
自首次提出此问题以来,规范发生了重大变化。新要求太明显了,无法理解。
答案 1 :(得分:0)
MySQL 5.6架构设置:
CREATE TABLE mydata
(`id` int, `trans_id` int, `CURRENT` double, `CUST_DATE` datetime)
;
INSERT INTO mydata
(`id`, `trans_id`, `CURRENT`, `CUST_DATE`)
VALUES
(16, 2362, 152.40, '2015-05-11 00:00:00'),
(16, 2363, 146.80, '2015-05-26 00:00:00'),
(16, 1669, 147.00, '2015-06-16 00:00:00'),
(16, 1979, 148.60, '2015-07-06 00:00:00'),
(16, 2344, 144.00, '2015-08-06 00:00:00'),
(104, 1280, 161.40, '2015-05-29 00:00:00'),
(104, 1553, 158.20, '2015-06-10 00:00:00'),
(104, 1898, 158.20, '2015-06-29 00:00:00'),
(104, 2131, 158.20, '2015-07-15 00:00:00'),
(104, 2223, 158.20, '2015-07-27 00:00:00'),
(104, 2294, 158.20, '2015-08-03 00:00:00')
;
查询1 :
SELECT id, MIN(CURRENT), MAX(CURRENT)
FROM mydata
GROUP BY ID
<强> Results 强>:
| id | MIN(CURRENT) | MAX(CURRENT) |
|-----|--------------|--------------|
| 16 | 144 | 152.4 |
| 104 | 158.2 | 161.4 |