2

我有以下架构,并希望找到首先出现的 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() 尝试了一些查询,但有点迷失了。

4

3 回答 3

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 小提琴演示

于 2012-08-20T10:38:43.070 回答
1

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

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。

于 2012-08-20T14:54:51.967 回答
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

示例小提琴

于 2012-08-20T10:32:23.723 回答