我完全陷入了疑问。 我有一个看起来像这样的查询:
select dr_machine,
dr_worker,
min(dr_date) as firstDate,
max(dr_date) as lastDate
from data
where dr_machine IS NOT NULL
&& dr_worker IS NOT NULL
group by dr_worker, dr_machine
order by dr_machine;
结果将是:
+------------+-------------------+------------+------------+
| dr_machine | dr_worker | firstDate | lastDate |
+------------+-------------------+------------+------------+
| KBA R- | john | 1242165600 | 1423350000 |
| KBA R- | peter | 1305237600 | 1316642400 |
| KBA R- | philip | 1248040800 | 1423522800 |
| Solna | marie | 1298453600 | 1378453600 |
| Solna | laura | 1278453600 | 1398453600 |
| Solna | anne | 1288453600 | 1388453600 |
+------------+-------------------+------------+------------+
我希望它显示dr_machine中的min和max dr_date,而不是dr_worker(就像现在一样) 所以结果如下:
+------------+-------------------+------------+------------+
| dr_machine | dr_worker | firstDate | lastDate |
+------------+-------------------+------------+------------+
| KBA R- | john | 1242165600 | 1423522800 |
| KBA R- | peter | 1242165600 | 1423522800 |
| KBA R- | philip | 1242165600 | 1423522800 |
| Solna | marie | 1278453600 | 1398453600 |
| Solna | laura | 1278453600 | 1398453600 |
| Solna | anne | 1278453600 | 1398453600 |
+------------+-------------------+------------+------------+
之前我将此结果与php中的另一个查询相结合,如下所示:
select dr_machine,
min(dr_date) as firstDate,
max(dr_date) as lastDate
from data
where dr_date IS NOT NULL
group by dr_machine;
我尝试过不同的连接和子查询,但说实话,我不知道自己在做什么,结果永远不会成为我想要的结果。
祝你好运 尼克拉斯
答案 0 :(得分:1)
我不是100%了解你的问题,但我的猜测是:
select data.dr_machine,
data.dr_worker,
t.firstDate,
t.lastDate
from data
left join(
select dr_machine,
min(dr_date) as firstDate,
max(dr_date) as lastDate
from data
group by dr_machine ) as t
on data.dr_machine = t.dr_machine
where data.dr_machine IS NOT NULL
&& data.dr_worker IS NOT NULL
order by data.dr_machine,data.dr_worker
答案 1 :(得分:0)
我首先编写一个查询,获取dr_machine的信息,就像你已经拥有的那样:
SELECT dr_machine, MIN(dr_date) AS firstDate, MAX(dr_date) AS lastDate
FROm data
WHERE dr_date IS NOT NULL
GROUP BY dr_machine;
然后,只需将该子查询与您的表一起加入dr_worker列:
SELECT d.dr_machine, d.dr_worker, tmp.firstDate, tmp.lastDate
FROM data d
JOIN(
SELECT dr_machine, MIN(dr_date) AS firstDate, MAX(dr_date) AS lastDate
FROM data
WHERE dr_date IS NOT NULL
GROUP BY dr_machine) tmp ON tmp.dr_machine = d.dr_machine AND dr_worker IS NOT NULL
GROUP BY d.dr_machine, d.dr_worker;