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)
 Difficult query?

Author  Topic 

cici
Starting Member

2 Posts

Posted - 2008-09-24 : 18:41:22
OK, I think this should be fairly easy, but I am having a brain fart and haven't been able to figure this one out. I have 2 tables:

subscription
------------
sub_id
parent_acct_id
package_id
start_date
end_date
next_sub_id
sub_active

subscription_package
--------------------
sub_id
product_id
child_acct_id

OK, part of the problem is the database design, but I can't do anything about that. The first table is kind of a sequence table in which the next_sub_id is a link to the next subscription valid for that account. The query I am trying to write is to get a list of all accounts (child_acct_id) of active subscriptions (sub_active = 1) for different packages (package_id) of the same product (product_id). I tried joining subscription to itself, but that only solved part of the problem. Any ideas would be appreciated. I hope that makes sense.

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2008-09-24 : 20:31:07
Any sample data and expected output?
Go to Top of Page

Ifor
Aged Yak Warrior

700 Posts

Posted - 2008-09-25 : 05:29:32
Difficult to say without DDL, sample data and expected output but something like the following may get you started:
;WITH cte (package_id, product_id, child_acct_id)
AS
(
SELECT S.package_id, SP.product_id, SP.child_acct_id
FROM subscription S
JOIN subscription_package SP
ON S.sub_id = SP.sub_id
WHERE S.sub_active = 1
)
SELECT DISTINCT C.product_id, C.child_acct_id
FROM cte C
JOIN
(
-- Products with multiple packages
SELECT D1.ProductID
FROM
(
SELECT DISTINCT C1.product_id, C1.package_id
FROM cte C1
) D1
GROUP BY D1.ProductID
HAVING COUNT(*) > 1
) D
ON C.product_id = D.product_id
ORDER BY product_id, child_acct_id

Go to Top of Page
   

- Advertisement -