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.
| Author |
Topic |
|
groston
Yak Posting Veteran
61 Posts |
Posted - 2009-10-21 : 00:26:54
|
Given a database with two tables:TABLE Items: ItemID integer, Description varchar, ItemTypeID integer andTABLE ItemTypes: ItemTypeID integer, Description varchar, Available integer The basic idea is that there can be no more Items of a particular ItemTypeID than Available.I would like to write a query which returns all of the records from the ItemTypes table for which the number of Items if less than Available.Let me give an example:Items:1, golf ball, 12, base ball, 13, basket ball, 14, pencil, 2ItemTypes:1, spheres, 32, cylinders, 4The query would return:2, cylinders, 4since there are already three spheres in the Items table.Thank you for your assistance! |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2009-10-21 : 00:48:32
|
[code]select *from ItemTypes twhere not exists ( select ItemTypeID from Items group by ItemTypeID having count(*) < t.Available )[/code] KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
sanoj_av
Posting Yak Master
118 Posts |
Posted - 2009-10-21 : 00:52:01
|
| select T.*from ItemTypes T, (Select ItemTypeID,count(1) as Available From Items Group By ItemTypeID)IWhere I.ItemTypeID=T.ItemTypeID AND T.Available >I.Available |
 |
|
|
groston
Yak Posting Veteran
61 Posts |
Posted - 2009-10-21 : 15:00:51
|
| khtan - your reply put me on the right track - thank you. Instead of 'not exists', I used 'not in'. I also changed the '<' to '>=". It works!Sanoj - I don't think that your approach works because if there is no Item of ItemType, then the record for that ItemType is not retrieved. However, your use of a query as a 'table' was a learning experience. Thank you. |
 |
|
|
|
|
|
|
|