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 |
dsvick
Starting Member
6 Posts |
Posted - 2011-11-18 : 10:50:17
|
Sorry for the poor subject, I wasn't sure how to word it. I have two tables one that contains a listing of purchase types with a typeID column and a description column. Then I have another table that is list of people and their spending limit by purchase type, it has columnsuserID intpurchaseTypeID intpurchaseLimit intI need to be able to get a list of everyone's purchase limits for each type of purchase. The problem is that everyone does not have an entry for each typeID and I need to get a result for every type for every person. Another way to put it is that if a person has limit set for one or more types I need to that person to appear in the result set with a record for every type.Here is short example:purchaseTypeId desc1 books2 movies3 musicuserID typeID limit1 1 1001 2 3001 3 5002 1 1002 2 3003 1 503 2 4003 3 8004 1 254 2 200I need to run a query that will give me results like:purchType userID limitbooks 1 100movies 1 300music 1 500books 2 100movies 2 300music 2 nullbooks 3 50movies 3 400music 3 800books 4 25movies 4 200music 4 null IF I do this with a left join I only get a single row for music with both userID and limit being null. I know I could this in the code with multiple calls to the DB, but I wanted to see if there was a recommended way to do it using SQL first. I looked at CTEs but I don't think that they are the way to go. Is my best bet going to be to use cursors in the stored procedure?thanks, if that is not enough info let me know, I appreciate any input or nudges in the right direction.Dave |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-11-18 : 10:54:21
|
[code]SELECT p.[desc] as purchType,s.userID,m.limitFROM purchase_types pCROSS JOIN (SELECT DISTINCT userID FROM SpendingTable) sLEFT JOIN SpendingTable mON m.userID = s.userIDAND m.typeID = p.PurchaseTypeID [/code]I've assumed table names in above query, make sure you use actual names instead------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
dsvick
Starting Member
6 Posts |
Posted - 2011-11-18 : 11:34:59
|
WOW!!! Thanks visakh!! That is completely awesome and much easier than I thought it would be. I looked at cross joins for about 10 seconds and didn't think they'd work.I appreciate the quick response!Dave |
 |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2011-11-18 : 11:36:27
|
welcome------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
 |
|
|
|
|