开发者

T-SQL Subquery Question

开发者 https://www.devze.com 2022-12-31 12:33 出处:网络
i have two queries. For each tuple of query1 i want to run query2. i dont want 开发者_如何学运维to use cursors. i tried several approaches using subqueries.

i have two queries. For each tuple of query1 i want to run query2. i dont want 开发者_如何学运维to use cursors. i tried several approaches using subqueries.

query1:

select 
    distinct 
    category, 
    Count(category) as CategoryCount
from 
    mytable 
group by 
    category

query2:

select
   top 3 
   Text,
   Title,
   Category
from
    mytable
where
    Category = '1'

Category = '1' is a sample. the value should come from query1


Try this

WITH TBL AS
(
SELECT TEXT, TITLE, CATEGORY,
       COUNT(*) OVER(PARTITION BY CATEGORY) AS CATEGORYCOUNT,
       ROW_NUMBER() OVER(PARTITION BY CATEGORY ORDER BY (SELECT 0)) AS RC
FROM MYTABLE
)
SELECT TEXT, TITLE, CATEGORY, CATEGORYCOUNT
FROM TBL
WHERE RC <= 3
ORDER BY CATEGORY
0

精彩评论

暂无评论...
验证码 换一张
取 消