I have a table schema that looks like this
CREATE TABLE [dbo].[Discounts](
[Id] [int] NOT NULL,
[ProductId] [varchar(50)] NOT NULL,
[LowerBoundDays] [int] NOT NULL,
[UpperBoundDays] [int] NOT NULL,
[Discount] [decimal](18, 4) NOT NULL,
And some data like this
lower upper discount(%)
product1 0 10 0
product1 10 30 1
product1 30 60 2
product1 60 90 3
product1 90 120 4
product2 0 10 0
product2 10 30 1
product2 30 60 2
product2 60 90 3
product2 90 120 4
How can I do a pivot query to get 2 rows that look like this:
0-10 10-30 30-60 60-90 90-120
product1 0 1 2 3 4
product2 0 1 2 3 4
Since you are using SQL Server, there are several ways that you can convert the rows of data into columns.
You can use an aggregate function with a CASE expression to get the result:
See SQL Fiddle with Demo.
If you are using SQL Server 2005+, then you can use the PIVOT function:
See SQL Fiddle with Demo.
The above two version work great if you have a known number of values, but if you have an unknown number of ranges, then you will need to to use dynamic SQL:
See SQL Fiddle with Demo. All versions will give a result: