T-SQL子查询问题

时间:2010-05-19 10:20:05

标签: sql tsql

我有两个问题。 对于query1的每个元组,我想运行query2。我不想使用游标。我尝试了几种使用子查询的方法。

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'是一个示例。该值应来自query1

1 个答案:

答案 0 :(得分:1)

试试这个

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