以下是我桌子的结构。我想要标记为蓝色的行。即使使用多个分组,我的查询也无法正常工作。
SELECT * FROM drug_refills WHERE drug_inventory_id = 1 GROUP BY drug_entity_id, start_date
对于蓝色标记,日期为最大值,后跟drug_entity_id(分组依据)
答案 0 :(得分:1)
使用相关子查询建立最后日期
drop table if exists t;
create table t(drug_refill_id int auto_increment primary key,drug_inventory_id int,drug_entity_id int,start_date date);
insert into t (drug_inventory_id,drug_entity_id, start_date) values
(1,1,'2018-01-01'),(1,3,'2018-01-02'),(2,4,'2018-01-01'),(1,5,'2018-01-01'),(1,5,'2018-02-01');
select *
from t
where start_date = (select max(start_date) from t t1 where t1.drug_entity_id = t.drug_entity_id) and
drug_inventory_id = 1;
+----------------+-------------------+----------------+------------+
| drug_refill_id | drug_inventory_id | drug_entity_id | start_date |
+----------------+-------------------+----------------+------------+
| 1 | 1 | 1 | 2018-01-01 |
| 2 | 1 | 3 | 2018-01-02 |
| 5 | 1 | 5 | 2018-02-01 |
+----------------+-------------------+----------------+------------+
3 rows in set (0.00 sec)
顺便说一句,如果您希望答案更接近您的数据,那么在您的问题中将数据包含为文本而不是图像。