我的数据是这样的:
Client Number | Order Date | Order Amount | Sequence (created with Row_Number())
我用Row_Number()创建了一个序列,所以我可以看到客户端有多少订单。
如果我使用WHERE序列> 3,我在3之前丢失了订单。我无法使用HAVING,因为我需要查看每个订单。如何选择超过3个订单的客户编号?
我想看看:
Client Number | Order Date | Order Amount | Sequence
1111 Jan 01 100 1
1111 Jan 02 100 2
1111 Jan 03 100 3
1112 Jan 01 100 1
1112 ... ... ...
1112 Jan 20 100 20
所以只有序列大于3的那些,同时仍然保持序列1和2的行。
答案 0 :(得分:2)
SELECT *
FROM data
WHERE ClientNumber IN
(
SELECT ClientNumber
FROM data
GROUP BY ClientNumber
HAVING COUNT(1) >= 3
);
答案 1 :(得分:0)
create table #test(clientnumber int, orderdate datetime, orderamount int)
insert into #test values
(1110, '01/01/2016', 100),
(1110, '01/02/2016', 100),
(1111, '01/01/2016', 100),
(1111, '01/02/2016', 100),
(1111, '01/03/2016', 100),
(1112, '01/01/2016', 100),
(1112, '01/02/2016', 100),
(1112, '01/03/2016', 100),
(1112, '01/04/2016', 100);
with cte as(
select clientnumber, orderdate, orderamount,
count(*) over(partition by clientnumber ) as ran
from #test)
select * from cte
where ran >= 3