这是我当前查询所产生的:
EventID Sku User1 LogTime
3510 02821-99-0 Item Inducted 2019-07-08
3510 02821-99-0 Item Inducted 2019-07-06
3510 12573-88-L Item Inducted 2019-07-08
3510 12573-88-L Item Inducted 2019-07-07
3510 12948-96-M Item Inducted 2019-07-06
3510 12948-96-M Item Inducted 2019-07-05
3510 12948-96-M Item Inducted 2019-07-05
我想要的是:(每个SKU的最新事件ID 3510)
EventID Sku User1 LogTime
3510 02821-99-0 Item Inducted 2019-07-08
3510 12573-88-L Item Inducted 2019-07-08
3510 12948-96-M Item Inducted 2019-07-06
我尝试使用MAX FUNCTION,但查询失败。
以下是我当前正在使用的查询:
select
tl.EventID,
tl.Sku,
tl.User1,
--MAX(tl.LogTime) as 'LogTime'
tl.LogTime
from dmhost.tblTransactionLog tl
where tl.logTime between '7/5/2019' and '7/9/2019'
and tl.sku not like 'NULL'
and tl.sku <> ''
and tl.sku not like 'Unknown'
and tl.EventID like '3510'
--group by tl.Sku,tl.EventID
order by tl.Sku
我评论了我尝试过的内容。 谢谢!
答案 0 :(得分:2)
这将在SQL Server和MySQL中工作。 (https://www.db-fiddle.com/f/kDhqfwDG2bUcqm5GKUbdj3/0)
首先为EventID和Sku的每种组合获取最大LogTime,然后从tblTransactionLog加入该日志。
SELECT tl.EventID
, tl.Sku
, tl.User1
, tl.LogTime
FROM dmhost.tblTransactionLog tl
INNER JOIN (
SELECT EventID
, Sku
, MAX(LogTime) AS MaxLogTime
FROM dmhost.tblTransactionLog
WHERE LogTime BETWEEN '7/5/2019' AND '7/9/2019'
GROUP BY EventID, Sku
) AS tmax ON tl.EventID = tmax.EventID
AND tl.Sku = tmax.Sku
AND tl.LogTime = tmax.MaxLogTime
WHERE tl.LogTime BETWEEN '7/5/2019' AND '7/9/2019'
答案 1 :(得分:0)
对于按row_number()
和EventID
列进行分区,以及由于Sku
采用最新的LogTime
分区,您可以使用窗口分析功能order by LogTime desc
:< / p>
select q.EventID, q.Sku, q.User1, q.LogTime
from
(
select tl.EventID, tl.Sku, tl.User1, t1.LogTime
row_number() over (partition by tl.EventID, t1.Sku order by tl.LogTime desc) as rn
from dmhost.tblTransactionLog tl
where tl.logTime between '2019-07-05' and '2019-07-09'
and tl.sku not like 'NULL'
and tl.sku <> ''
and tl.sku not like 'Unknown'
and tl.EventID like '3510'
) q
where rn = 1
order by q.Sku
答案 2 :(得分:0)
我建议将此查询写为:
select tl.EventID, tl.Sku, tl.User1, tl.LogTime
from (select tl.*,
row_number() over (partition by tl.EventID, tl.sku order by tl.logTime desc) as seqnum
from dmhost.tblTransactionLog tl
where tl.logTime >= '2019-07-05' and
tl.logtime < '2019-07-09' and
tl.sku not in ('NULL', '', 'Unknown') and
tl.EventID like 3510
) tl
where seqnum = 1
order by tl.Sku;
注意:
comparisons on
sku is simplified using
字符串不可用。EventID
看起来像一个数字,所以我假设它是数字,并删除了引号进行比较,并将LIKE
更改为=
。BETWEEN
与日期/时间值一起使用。