tags:

views:

56

answers:

1

Hi,

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

+1  A: 

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
Chris Bednarski
Invalid column name 'RC'.
Snoopy
which version of SQL are you running? This will not work on 2000. Only 2005+
Chris Bednarski
but without the WHERE RC <= 3 exactly what i want.
Snoopy
select @@version returns Microsoft SQL Server 2005 - 9.00.4035.00 (X64) Nov 24 2008 16:17:31 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition (64-bit) on Windows NT 5.2 (Build 3790: Service Pack 2)
Snoopy
changed the query
Chris Bednarski
the with works but gives wrong results ;-(
Snoopy
which part is wrong?
Chris Bednarski
it looks like the distinct is applied and the top is ignored.
Snoopy
@Nick: You should get a maximum of 3 rows per category with this query. However, there could be less
Chris Bednarski
I try to analyze this. Need to do some smaller test data. Come back to you soon!
Snoopy
Thanks Chris. I Added an order and the results are good!
Snoopy