sql查询总和计数

时间:2014-08-06 07:48:28

标签: sql count sum aggregate-functions

我有一张桌子

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"只有先前的状态是"检查"时才应计算状态。 请帮助我或给出正确的解决方案

1 个答案:

答案 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

Fiddler Demo

<强> 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

Fiddler Demo

<强>的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

Fiddler Demo

实际上,第三种情况可以解决很多问题。