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
 T Sql query

Author  Topic 

dotnet2010
Starting Member

7 Posts

Posted - 2013-07-09 : 00:06:21
I have a packages and items
Each package has more than one item with status
The package got his status from the items
I want two query that can show for me how many packages that didn't have the same status of at least one of his items
The second show the packlist if not all his items have the same status as his status

Package
PackageId StatusId
1 -------- 1
2 -------- 2
3 -------- Null

Item
ItemId PackageId StatusID Date
1 -------- 1 -------- 1 ------ 1/1/2000
2 -------- 1 --------1 -------- 1/1/2001
3 -------- 3 -------- 2 -------- 1/1/2001
4 -------- 3 -------- 2 -------- 1/2/2001
5 -------- 2 -------- 2 -------- 1/2/2001
6 -------- 2 -------- 3 -------- 1/3/2001

So the first query will show PackageID 3 that hasn't the same status as his items it is null
with these details
PackageId and one of the dates of the items.

the second query will show packlageId 2 and Package Id 3
with the same details

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-09 : 01:13:02
do you mean this for first scenario?

SELECT p.PackageID,MAX(i.Date)
FROM Item i
INNER JOIN Package p
ON p.PackageID = i.PackageID
GROUP BY p.PackageID
HAVING SUM(CASE WHEN i.StatusId <> COALESCE(p.StatusId,-1) THEN 1 ELSE 0 END) =0



SELECT p.PackageID,MAX(i.Date)
FROM Item i
INNER JOIN Package p
ON p.PackageID = i.PackageID
GROUP BY p.PackageID
HAVING SUM(CASE WHEN i.StatusId = COALESCE(p.StatusId,-1) THEN 1 ELSE 0 END) =0


and for second


SELECT p.PackageID,MAX(i.Date)
FROM Item i
INNER JOIN Package p
ON p.PackageID = i.PackageID
GROUP BY p.PackageID
HAVING SUM(CASE WHEN i.StatusId <> COALESCE(p.StatusId,-1) THEN 1 ELSE 0 END) > 0


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -