Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Count of a complex query

Author  Topic 

aberbotimue
Starting Member

26 Posts

Posted - 2009-11-19 : 07:41:25
Hi guys..

I have this sql


select Item,itemid,averate,tally, COUNT(*) AS hits
FROM (SELECT Item, itemid,averate,tally
FROM Items
WHERE Item LIKE '%nokia%'
UNION ALL
SELECT Item, itemid,averate,tally
FROM Items WHERE Item LIKE '%tablet%') AS d
GROUP BY Item, itemid,averate,tally
order by hits desc


It works great..

the importanbt part, is it removes the duplicates for me, and counts howmany their were, putting the results in order for me, based on how many of the search terms it found. and with more search terms, I just add another UNION ALL..

I only ever show 100 results at a time, on a web page, but want to show the total results..

I have tried with no sucess...

I can either return another col, with the total count, or run a second query that will give me the count..

neither of which I can figure out...

any help would be apreciated..

Ifor
Aged Yak Warrior

700 Posts

Posted - 2009-11-19 : 08:31:20
Maybe something like:

;WITH SearchConds(SearchText)
AS
(
SELECT 'nokia'
UNION ALL SELECT 'tablet'
)
,ItemHits
AS
(
SELECT Item, itemid, averate, tally
,COUNT(*) AS hits
FROM Items I
JOIN SearchConds S
ON I.Item LIKE '%' + S.SearchText + '%'
GROUP BY Item, itemid, averate, tally
)
,TotalCount
AS
(
SELECT COUNT(*) As TotalHits
FROM Items I
JOIN SearchConds S
ON I.Item LIKE '%' + S.SearchText + '%'
)
SELECT TOP 100 *
FROM ItemHits
CROSS JOIN TotalCount
ORDER BY hits DESC

Go to Top of Page

aberbotimue
Starting Member

26 Posts

Posted - 2009-11-19 : 08:44:07
Thanks IFor

Wasn't an easy question I had then!!

I was passing the original query in from code.. I assume this is somthing I need to run as a stored proc?

SQL is not my streanth!

Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 2009-11-19 : 09:40:34
There is no reason why the SQL cannot be passed from code although a SP would be better.

ps The CTE structure assumes SQL2005 or above. If you are using SQL2000, just use derived tables instead.
Go to Top of Page
   

- Advertisement -