我有以下架构,想要找到首先出现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()的查询,但有点丢失。
答案 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
答案 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
答案 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。