user998405
user998405

Reputation: 1339

Display database record as matrix style

Is it possible to use select statement to select data from a database as matrix style?

Below is my table

ProductID Size Quantity
p001       37    2
p001       38    2
p001       39    3
p003       40    1
p004       41    1  

I want to display those record like below

Product ID  37  38  39 40  41
p001        2   2   3  0   0
p003        0   0   0  1   0

The column size is dynamic. Is it possible to select data like my example at above? Please help. Thanks in advance.

Upvotes: 1

Views: 1672

Answers (3)

Thakur
Thakur

Reputation: 2020

Check below link for reference

http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables

Create Below procedure

CREATE PROCEDURE [dbo].[crosstab] 
@select varchar(8000),
@sumfunc varchar(100), 
@pivot varchar(100), 
@table varchar(100) 
AS

DECLARE @sql varchar(8000), @delim varchar(1)
SET NOCOUNT ON
SET ANSI_WARNINGS OFF

print ('SELECT ' + @pivot + ' AS [pivot] INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('SELECT ' + @pivot + ' AS [pivot] INTO ##pivot FROM ' + @table + ' WHERE 1=2')
EXEC ('INSERT INTO ##pivot SELECT DISTINCT ' + @pivot + ' FROM ' + @table + ' WHERE ' 
+ @pivot + ' Is Not Null')

SELECT @sql='',  @sumfunc=stuff(@sumfunc, len(@sumfunc), 1, ' END)' )

SELECT @delim=CASE Sign( CharIndex('char', data_type)+CharIndex('date', data_type) ) 
WHEN 0 THEN '' ELSE '''' END 
FROM tempdb.information_schema.columns 
WHERE table_name='##pivot' AND column_name='pivot'

SELECT @sql=@sql + '''' + convert(varchar(100), [pivot]) + ''' = ' + 
stuff(@sumfunc,charindex( '(', @sumfunc )+1, 0, ' CASE ' + @pivot + ' WHEN ' 
+ @delim + convert(varchar(100), [pivot]) + @delim + ' THEN ' ) + ', ' FROM ##pivot

DROP TABLE ##pivot

SELECT @sql=left(@sql, len(@sql)-1)
SELECT @select=stuff(@select, charindex(' FROM ', @select)+1, 0, ', ' + @sql + ' ')

EXEC (@select)
SET ANSI_WARNINGS ON
GO

and then use the procedure as below

EXECUTE crosstab @select = 'Select productid from Products',
                 @sumfunc = 'AVG(Quantity)',
                 @pivot = 'Size', 
                 @table = 'Product'

Stackoverflow reference - SQL Rows to Columns

Upvotes: 1

Abdul Ahad
Abdul Ahad

Reputation: 2221

you need to use PIVOT.

hope this will help you,

DECLARE @columns VARCHAR(8000)

SELECT @columns = COALESCE(@columns + ',[' + cast(Size as varchar) + ']',
'[' + cast(Size as varchar)+ ']')
FROM MyTable

DECLARE @query VARCHAR(8000)

SET @query = '
SELECT *
FROM MyTable
PIVOT
(
MAX(Quantity)
FOR [Size]
IN (' + @columns + ')
)
AS p'

EXECUTE(@query)

For more about PIVOT, take a look at here

Upvotes: 0

hkf
hkf

Reputation: 4520

You'll need to use PIVOT()

http://msdn.microsoft.com/en-us/library/ms177410.aspx

It's not the simplest function but it will do what you are asking for.

Upvotes: 0

Related Questions