日期:2014-05-18  浏览次数:20474 次

sql 开窗函数如何处理条件
请教sql 开窗函数如何处理条件呢?
比如我想查找商品表中,每种类型各有多少种商品,条件是每类商品数量不能小于10.如何写?
select COUNT(goodstype) as goodscount,goodstype from tbGoods group by goodstype having COUNT(goodstype)>10
用partition by如何处理
select distinct COUNT(goodstype) over(partition by goodstype) as goodscount,goodstype from tbGoods???

------解决方案--------------------
SQL code

declare @tbGoods table (goodstype varchar(1))
insert into @tbGoods
select 'a' union all
select 'a' union all
select 'a' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b' union all
select 'b'

select COUNT(1) as goodscount,goodstype from @tbGoods 
group by goodstype having COUNT(goodstype)>10
/*
goodscount  goodstype
----------- ---------
12          b
*/

SELECT ROW_NUMBER() OVER (PARTITION BY goodstype ORDER BY (SELECT 1)) AS rid,* FROM @tbGoods
/*
rid                  goodstype
-------------------- ---------
1                    a
2                    a
3                    a
1                    b
2                    b
3                    b
4                    b
5                    b
6                    b
7                    b
8                    b
9                    b
10                   b
11                   b
12                   b
*/