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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Help in SQL query

Author  Topic 

Johnnybax
Starting Member

3 Posts

Posted - 2012-06-05 : 11:52:38
I have order table and member table.

table-1: Orders
-------------
orderid int PK
memberid in FK members(memberid)

Table-2: Members
----------------
memberid int PK


I have application that returns results based on user input

totalOrders: textbox field where user can enter 0,1,2...
drop down: Greater than, less than, equal to

Based on these 2 fields selection. I want to get results from above database tables

If user enters 2 in textbox and selects "less than" operator then it should return members who never placed order and who placed order 1 time only.

Issue is order table does not have any memberid if member never placed order.

How should I return results using SQL query?

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2012-06-05 : 12:04:13
select m.memberid, numorders = sum(case when o.memberid is null then 0 else 1 end)
from Members m
left join Orders o
on m.memberid = o.memberid
group by m.memberid
having count(*) = 1

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-05 : 12:37:24
[code]
select m.*
from Mambers m
outer apply (select count(orderid) as ordcnt
from Orders
where memberid = m.memberid
)o
where ((coalesce(ordcnt,0)=@totalOrders and @operator='equal to')
or (coalesce(ordcnt,0)<@totalOrders and @operator='less than')
or (coalesce(ordcnt,0)>@totalOrders and @operator='greater than'))
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -