2017-07-27 95 views
1

假設我有一個表foo從中我想從每個類別中選擇N行SQL動態計數選擇

create table foo(name text, category text); 

name | category 
------+---------- 
aaa | cat1 
bbb | cat1 
ccc | cat2 
ddd | cat2 
eee | cat2 

現在,我想從foo到挑賦予了許多類別

category | count 
----------+------- 
cat2  |  2 
cat1  |  1 

結果應該是3行

name 
------ 
ccc 
ddd 
aaa 

-- wrong, not taking counts into account 
with t as (select * from (values ('cat1', 1), ('cat2', 2)) as 
t(category, count)) select name from foo, t where foo.category = t.category; 

name 
------ 
aaa 
bbb 
ccc 
ddd 
eee 

(關係可以隨機地或通過任何順序來解決)我可以用多個查詢來做到這一點,但我認爲我錯過了一些非常明顯的事情,並且可以通過單個查詢來完成選擇。

回答

1

你會使用row_number()

select foo.* 
from (select t.*, 
      row_number() over (partition by foo.category order by foo.category) as seqnum 
     from foo join 
      t 
      on foo.category = t.category 
    ) t 
where seqnum <= t.cnt;