Here’s the deal…I need to create a simple bar graph with price distillations for Crystal Reports XI. CR has a fun feature where is a datapoint has no data it skips it in the graph. That is, say I run it and there is no data that meets the <$100,000 criteria. Well, the graph then visually starts at $125,000 skipping <$100,000 completely. This applies when using straight up SQL Server tables to drive the graphs. Using stored procedures to specify that a specific datapoint is zero is the way around it.
So, I need create a query that will make sure all datapoints are captured. I’m working with a consultant who created a stored procedure using a loop, but I’d be MUCH happier to rely on just sql queries.
Here is the output from his stored procedure that I’d like to mimic:
Idx valuerange valuecount
1 <100 180
2 125 78
3 150 88
4 175 60
5 200 48
6 225 44
7 250 45
8 275 26
9 300 34
10 325 16
11 350 19
12 375 8
13 400 11
14 425 3
15 450 7
16 475 4
17 500 8
18 525 0
19 550 2
20 550+ 13
Note that idx 18 with the 525 value is 0, yet 525 still exists to be reported on.
And here is the stored procedure he used to make it happen (spoilered for brevity’s sake):
[spoiler]USE [Builder Report MatrixSQL]
GO
/****** Object: StoredProcedure [dbo].[RptBarActiveResale] Script Date: 07/21/2011 21:27:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[RptBarActiveResale]
(
@Region varchar(25) = NULL,
@County varchar(25) = NULL,
@Schooldistrict varchar(50) = NULL,
@Zip varchar(25) = NULL,
@DateTo smalldatetime
)
AS
SET NOCOUNT ON
CREATE TABLE #Report (Idx int identity(1,1), valuerange varchar(200), valuecount int)
declare @i integer
SET @i = 125
INSERT INTO #Report (valuerange) VALUES (’<100’)
WHIlE @i <= 550
BEGIN
INSERT INTO #Report (valuerange) VALUES (Convert(varchar, @i))
SET @i = @i + 25
END
INSERT INTO #Report (valuerange) VALUES (‘550+’)
UPDATE #Report Set ValueCount =
COALESCE((SELECT SUM(a.RecordCount)
FROM ActiveRngAggregates as a
WHERE a.ValueRange = #Report.valuerange
and (a.county like isnull(@County, a.county) + ‘%’)
and (a.mlssource like isnull(@Region, a.mlssource) + ‘%’)
and (a.schooldistrict like isnull(@Schooldistrict, a.schooldistrict) + ‘%’)
and (a.zip like isnull(@Zip, a.zip) + ‘%’)
and a.dateaddedmonth = month(@DateTo)
and a.dateaddedyear = year(@DateTo)
and a.new <> ‘Yes’
and a.status <> ‘Sold’) ,0)
SELECT * FROM #Report
DROP TABLE #Report[/spoiler]
What I’m looking for is to find out if this can even be done without loops, and if so how would I begin? and if loops are indeed required, is the code above the way to do it? I’m no sql (in general) dummy yet far from an expert, but this I just can’t quite get my head around.
Thanks!
Jeff