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 2005 Forums
 Transact-SQL (2005)
 query result

Author  Topic 

Peter99
Constraint Violating Yak Guru

498 Posts

Posted - 2011-08-04 : 19:21:00
I have 3 tables with sample data

USERS
table User_id (PK) (generated via a sequence),Email,Gender,Age,Name
1 a@a.com m 30 rob
2 a@a.com m 31 robert
3 b@b.com f 18 lucie
4 b@b.com f 22 lulu
5 c@c.com m 10 kim
6 c@c.com f 18 kim
7 c@c.com f 08 kim
8 d@d.com f 18 JJ
9 d@d.com m 22 Jay
10 e@e.com f 88 Bill
11 e@e.com f 88 Will
12 e@e.com f 60 Will
13 f@f.com m 70 George

table SUBSCRIPTIONS columns: SUbscription_id (PK) (generated via a sequence) user_id (UK) (FK from users) subscription_type (UK) active_indicator
1 2 Magazine Yes
2 3 Music CD No
3 3 Magazine Yes

table TRANSACTIONS subscription_id (PK) (FK from subscriptions) action (PK) timestamp (PK)
1 Renewal 2002-sep-10
2 Renewal 2002-Jan-01
2 Cancellation 2002-Feb-01


The selection criteria is to limit the list to users which never subscribed to
anything; or;
users with inactive subscriptions; or;
users with active subscriptions that renewed between Sep 1st and sep 30th of any year

The output should be:
a@a.com m 31 robert
b@b.com f 22 lulu
c@c.com f 08 kim
d@d.com m 22 Jay
e@e.com f 60 Will0

what is sql query to achive this.

Thanks

sql-programmers
Posting Yak Master

190 Posts

Posted - 2011-08-04 : 22:56:13
Try this script,


SELECT #USERS.*,MONTH([timestamp]) FROM #USERS LEFT JOIN #SUBSCRIPTIONS ON #USERS.USER_ID=#SUBSCRIPTIONS.USER_ID
LEFT JOIN #TRANSACTIONS ON #TRANSACTIONS.subscription_id = #SUBSCRIPTIONS.SUbscription_id
WHERE #SUBSCRIPTIONS.USER_ID IS NULL OR #SUBSCRIPTIONS.active_indicator='Yes'
OR (MONTH([timestamp]) = 9)

SQL Server Programmers and Consultants
http://www.sql-programmers.com/
Go to Top of Page
   

- Advertisement -