是否可以使用select语句从数据库中选择数据作为矩阵样式?
以下是我的表
ProductID Size Quantity
p001 37 2
p001 38 2
p001 39 3
p003 40 1
p004 41 1
我想显示下面的记录
Product ID 37 38 39 40 41
p001 2 2 3 0 0
p003 0 0 0 1 0
列size
动态。是否可以像上面的例子一样选择数据?请帮忙。提前谢谢。
答案 0 :(得分:1)
您需要使用PIVOT
。
希望这会对你有所帮助,
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)
有关PIVOT
,take a look at here
答案 1 :(得分:1)
请查看以下链接以供参考
http://www.sqlteam.com/article/dynamic-cross-tabs-pivot-tables
创建以下程序
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
然后使用以下程序
EXECUTE crosstab @select = 'Select productid from Products',
@sumfunc = 'AVG(Quantity)',
@pivot = 'Size',
@table = 'Product'
Stackoverflow参考 - SQL Rows to Columns
答案 2 :(得分:0)