Grouping Results in SQL Server
I recently needed to send in a list of IDs to a query, and group the results by a set list of price ranges. At first this sounded really difficult, but after a little bit of thought, and planning, it was actually pretty simple. Take a look:
USE [databasename]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[getByPrice]
@prodIDs VARCHAR(MAX) = NULL,
--output params
@svrStatus INT OUTPUT,
@svrMessage VARCHAR(255)= NULL OUTPUT,
@svrCtrlName VARCHAR(255) = NULL OUTPUT,
@svrCtrlCode INT = NULL OUTPUT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @sql VARCHAR(8000)
DECLARE @rowCount INT
--initialize the error variable to zero
SET @svrStatus = @@error
BEGIN
SET @sql = 'SELECT b.min, b.max, count(price) as totals FROM
(SELECT minPrice as price FROM tablename WHERE productId IN ('+ CAST(@prodIDs AS VARCHAR(8000)) +')) a,
(SELECT 0 as min, 49.99 as max
UNION
SELECT 50 as min, 99.99 as max
UNION
SELECT 100 as min, 499.99 as max
UNION
SELECT 500 as min, 999.99 as max
UNION
SELECT 1000 as min, 1999.99 as max
UNION
SELECT 2000 as min, 10000 as max
) b
WHERE price >= b.min and price <=b.max
GROUP BY b.min, b.max
ORDER BY b.min'
EXEC (@sql)
END
SET @rowCount = @@rowCount
IF @rowCount = 0 BEGIN
SET @svrStatus = -1
SET @svrMessage = 'No records found'
SET @svrCtrlCode = 0
SET @svrCtrlName = 'errSystem'
END
END