November 18, 2013 at 6:14 pm
hi, all
I doing some stat reports, and every day it has different products (not all), but for my ssrs data set I want list for ALL products putting zeros if nothing found,
what is the nice way to achieve this. i.e. union complete list with actual results and replacing complete entry if entry present.
;with results as (
select 1 day, 100 amt union
select 2 day, 200 amt union
select 3 day, 300 amt union
-- select 4 day, 0 amt union -- nothing for day 4
select 5 day, 500 amt )
select * from results
1100
2200
3300
4 0 --* how to insert this ?
5500
Tx all
Mario
November 18, 2013 at 10:19 pm
Use a Tally table.
WITH results AS
(
SELECT 1 day, 100 amt UNION ALL
SELECT 2 day, 200 amt UNION ALL
SELECT 3 day, 300 amt UNION ALL
SELECT 5 day, 500 amt
),
Tally (n) AS
(
SELECT TOP 5 ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n1)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n2)
)
SELECT [day]=n, ISNULL(amt, 0)
FROM results a
RIGHT JOIN Tally b ON a.[day] = b.n;
My thought question: Have you ever been told that your query runs too fast?
My advice:
INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.
Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
Since random numbers are too important to be left to chance, let's generate some![/url]
Learn to understand recursive CTEs by example.[/url]
[url url=http://www.sqlservercentral.com/articles/St
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply