我有一张桌子
id date state
1 10.01.01 reg
2 08.01.01 reg
3 05.01.01 check
4 02.01.01 check
5 01.01.01 reg
并希望显示此结果
count reg
5 1
例如" reg"只有先前的状态是"检查"时才应计算状态。
请帮助我或给出正确的解决方案
答案 0 :(得分:2)
在 SQL Server 2012
及以上中,您可以使用LAG访问上一行值:
SQL SERVER 2012
;WITH MyCTE AS
(
select id, date,state,lag(state,1) over(order by id) as prevstate
from Table1
)
SELECT COUNT(*),SUM(CASE WHEN state = 'reg' AND prevstate = 'check' THEN 1 ELSE 0 END)
FROM MyCTE
<强> ORACLE 强>
With T AS
(
select "id", "date", "state", lag("state",1) over(order by "id") as "prevstate"
from Table1
)
SELECT COUNT(*),SUM(CASE WHEN "state" = 'reg' AND "prevstate" = 'check' THEN 1 ELSE 0 END)
FROM T
<强>的MySQL 强>
SELECT COUNT(*),SUM(CASE WHEN state = 'reg' AND prevstate = 'check' THEN 1 ELSE 0 END)
FROM
(
SELECT T1.ID,T1.Date,T1.state,T2.state AS prevstate
FROM Table1 T1
LEFT JOIN Table1 T2
ON T1.ID - 1 = T2.ID
) AS T
实际上,第三种情况可以解决很多问题。