NickD
NickD

Reputation: 2646

T-SQL Subquery Question

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

Upvotes: 0

Views: 157

Answers (1)

Chris Bednarski
Chris Bednarski

Reputation: 3434

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

Upvotes: 1

Related Questions