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
精彩评论