Reputation: 161
Here's a simple example of my problem. I have a stored proc that creates a report.
DECLARE @Report TABLE
(Product VARCHAR(10),
Purchases MONEY default (0)
)
DECLARE @Range TABLE
(minP MONEY,
maxP MONEY,
Descrip VARCHAR(50)
)
INSERT @Range
VALUES(0,1,'0-1'),
(2,5,'2-5'),
(6,10,'6-10')
INSERT @Report(Product, Purchases)
VALUES('A',1),
('A',5),
('B',10)
SELECT r.Product, r.Purchases, x.Descrip
FROM @Report r CROSS JOIN @Range x
WHERE r.purchases BETWEEN x.minp AND x.maxp
The results look like this:
Product Purchases Descrip
A 1.00 0-1
A 5.00 2-5
B 10.00 6-10
How can I get the results to look like this:
Product Purchases Descrip
A 1.00 0-1
A 5.00 2-5
A 0 6-10
B 0 0-1
B 0 2-5
B 10.00 6-10
Upvotes: 4
Views: 2786
Reputation: 56779
You could try something like this:
where
clause (plus linking product
)SELECT
r2.Product,
coalesce(r.Purchases, 0) as Purchases,
x.Descrip
FROM
(select distinct Product from @Report) r2 CROSS JOIN @Range x
left join @Report r on r.purchases BETWEEN x.minp AND x.maxp
and r.product = r2.product
| PRODUCT | PURCHASES | DESCRIP |
---------------------------------
| A | 1 | 0-1 |
| A | 5 | 2-5 |
| A | 0 | 6-10 |
| B | 0 | 0-1 |
| B | 0 | 2-5 |
| B | 10 | 6-10 |
I would assume your actual data is much more complicated than this. For instance, I'm not sure what kind of result you expect if there are multiple purchases within a single range. But this should at least get you started.
Upvotes: 3
Reputation: 70668
This should do it:
SELECT B.Product, ISNULL(C.Purchases,0) Purchases, A.Descrip
FROM @Range A
CROSS JOIN (SELECT DISTINCT Product
FROM @Report) B
LEFT JOIN @Report C
ON B.Product = C.Product
AND C.Purchases BETWEEN A.minP AND A.maxP
ORDER BY B.Product, Purchases
Here is a demo for you to try.
Upvotes: 4