SQL - 查找在另一个之前发生的总记录

时间:2012-08-20 10:28:57

标签: sql sql-server sql-server-2008

我有以下架构,想要找到首先出现typeId为10的客户端数量。以下数据的答案为2(客户ID为1000和1003,1月1日为10,1月2日为11。

CREATE TABLE Event (ClientId int, TypeId int, Date smalldatetime)
INSERT Event (ClientId , TypeId, Date) VALUES (1000, 10, '1 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1000, 11, '2 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1001, 11, '1 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1001, 10, '2 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1002, 11, '1 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1003, 10, '1 JAN 12')
INSERT Event (ClientId , TypeId, Date) VALUES (1003, 11, '2 JAN 12')

我尝试了一些ROW_NUMBER()的查询,但有点丢失。

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT a.* FROM 
    (SELECT CLIENTID,TYPEID,MIN(DATE) AS DATE
     FROM EVENT
     GROUP BY CLIENTID, TYPEID)A
JOIN
    (SELECT CLIENTID,MIN(DATE) AS DATE
     FROM EVENT
     GROUP BY CLIENTID)B
 ON   B.CLIENTID=A.CLIENTID
 AND  B.DATE=A.DATE
 WHERE TYPEID=10


SQL Fiddle Demo

答案 1 :(得分:1)

您可以尝试以下操作。

  • 自我加入ClientID
  • 上的表格
  • 仅当自联接表的typeID更大时
  • 并且自联接表的Date更大

SQL声明

SELECT e1.*
FROM   Event e1
       INNER JOIN Event e2 ON e2.ClientID = e1.ClientID
                              AND e2.TypeID > e1.TypeID
                              AND e2.Date > e1.Date
WHERE  e1.TypeID = 10

Example Fiddle

答案 2 :(得分:1)

您可以使用两个row_number()s执行此操作:

select count(*)
from (select e.*,
             row_number() over (partition by clientId order by date) as seqnum,
             row_number() over (partition by clientId, typeid order by date) as ct_seqnum
      from event e
     ) e
where seqnum = 1 and ct_seqnum = 1 and typeid = 10

这是按类型进行整体排序和排序。你的条件相当于说这两个在typeid为10的行上是1。