我正在尝试查找故障单更改所有者组的次数。我正在使用此查询:
SELECT
TICKETID, CHANGEDATE, OWNERGROUP,
RANK() OVER (Partition by TICKETID, OWNERGROUP ORDER BY CHANGEDATE) rk
FROM TKSTATUS where TICKETID= '12345' order by CHANGEDATE
得到了这个结果集: enter image description here
在我数1后......得到4。
我期待这个结果但是找不到我怎么做:
RK
1
1
2
1
2
3
1
1
1
2
3
,结果为6.
我知道不是这样做的,因为它会在排名前将TICKETID
和OWNERGROUP
分组。
我会继续找到一种方法来做到这一点,但我想看看是否有人有想法。
答案 0 :(得分:1)
在SQL Server 2012中,您可以使用lag()
通过将当前行值与前一行值OwnerGroup
进行比较来查看OwnerGroup
更改的数量。
select
TicketId
, ChangeDate
, OwnerGroup
, OwnerGroupChange = case
when coalesce(OwnerGroup,'')
= lag(coalesce(OwnerGroup,'')) over (partition by TicketId order by ChangeDate)
then 0
else 1
end
from TkStatus
where TicketId = '12345'
order by ChangeDate
要获取更改数量,您可以将上述内容用作子查询或公用表表达式:
select
TicketId
, OwnerGroupChange = sum(OwnerGroupChange)
from (
select
TicketId
, ChangeDate
, OwnerGroup
, OwnerGroupChange = case
when coalesce(OwnerGroup,'')
= lag(coalesce(OwnerGroup,'')) over (partition by TicketId order by ChangeDate)
then 0
else 1
end
from TkStatus
where TicketId = '12345'
) s
在SQL Server 2012之前,您可以使用outer apply()
来获取之前的OwnerGroup
,如下所示:
select
t.TicketId
, t.ChangeDate
, t.OwnerGroup
, OwnerGroupChange = case
when coalesce(t.OwnerGroup,'') = coalesce(x.OwnerGroup,'')
then 0
else 1
end
from TkStatus t
outer apply (
select top 1
i.OwnerGroup
from TkStatus i
where i.TicketId = t.TicketId
and i.ChangeDate < t.ChangeDate
order by i.ChangeDate desc
) x
where t.TicketId = '12345'
order by t.ChangeDate
答案 1 :(得分:0)
SELECT
TICKETID, CHANGEDATE, OWNERGROUP,
DENSE_RANK() OVER (Partition by TICKETID ORDER BY CHANGEDATE) as RK
FROM TKSTATUS where TICKETID= '12345' order by CHANGEDATE
答案 2 :(得分:0)
你可以像这样使用CTE和LAG函数:
WITH CTE_Tickets as
( SELECT
TICKETID, CHANGEDATE, OWNERGROUP,
LAG(OWNERGROUP, 1) OVER (Partition by OWNERGROUP ORDER BY CHANGEDATE, OWNERGROUP ) as Prev
FROM TKSTATUS where TICKETID= '12345')
SELECT
TICKETID, CHANGEDATE, OWNERGROUP, Prev ,
IIF(OWNERGROUP=Prev, 0, 1) as changestatus
FROM CTE_Tickets
ORDER BY CHANGEDATE , OWNERGROUP