使用以下查询
SELECT evhist_XPK.event_date, evhist_XPK.zone_id, system.account
FROM evhist_XPK INNER JOIN
system ON evhist_XPK.system_no = system.system_no INNER JOIN
site ON system.site_no = site.site_no INNER JOIN
event ON event.event_id=evhist_XPK.event_id
WHERE (evhist_XPK.event_id = '7381') AND (evhist_XPK.event_date >= DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0))
ORDER BY system.account
我明白了
event_date zone_id account
2019-01-22 07:10:10.607 9 V0137C4
2019-01-22 07:10:12.637 10 V0137C4
2019-01-23 08:44:50.737 9 V0137C4
2019-01-23 08:44:50.907 10 V0137C4
2019-01-23 21:01:09.523 9 V0137C4
2019-01-23 21:01:09.540 10 V0137C4
2019-01-24 06:58:44.107 9 V0137C4
2019-01-24 06:58:46.137 10 V0137C4
2019-01-25 07:24:07.000 9 V0137C4
2019-01-25 07:24:07.080 10 V0137C4
2019-01-28 06:54:53.507 9 V0137C4
2019-01-28 06:54:53.600 10 V0137C4
2019-01-29 07:45:10.520 9 V0137C4
2019-01-29 07:45:12.597 10 V0137C4
2019-01-29 07:45:21.520 12 V013708
2019-01-29 07:45:32.597 13 V013708
2019-01-29 07:45:35.520 11 V013708
2019-01-29 07:45:38.620 11 V013708
但是我需要获得以下这些记录,以及不同帐户的每个zone_id的最大日期时间
2019-01-29 07:45:10.520 9 V0137C4
2019-01-29 07:45:12.597 10 V0137C4
2019-01-29 07:45:21.520 12 V013708
2019-01-29 07:45:32.597 13 V013708
2019-01-29 07:45:38.620 11 V013708
答案 0 :(得分:0)
您可以使用窗口功能。例如:
WITH q as (<your query here without the order by>)
SELECT q.*
FROM (SELECT q.*, ROW_NUMBER() OVER (PARTITION BY zone_id, account ORDER BY event_date DESC) as seqnum
FROM q
) q
WHERE seqnum = 1
ORDER BY account;
或者一个有趣的方法就是简单地添加:
答案 1 :(得分:0)
您还可以执行以下操作,这更简单:
SELECT MAX(event_date), zone_id, account
FROM
(
--Your query
SELECT evhist_XPK.event_date, evhist_XPK.zone_id, system.account
FROM evhist_XPK
INNER JOIN system
ON evhist_XPK.system_no = system.system_no
INNER JOIN site
ON system.site_no = site.site_no
INNER JOIN event
ON event.event_id = evhist_XPK.event_id
WHERE (evhist_XPK.event_id = '7381')
AND (evhist_XPK.event_date >= DATEADD(day, DATEDIFF(day, 1, GETDATE()), 0))
) t1
GROUP BY zone_id, account
ORDER BY account;