我是sql开发的新手。我想要一个动态的交叉表查询。让我先解释一下我的表格。我有一张表SalesOrder。每个SalesOrder都有SalesItems。每个项目都有productID,每个产品都有fabricID。每个SalesItem都有一个字段lengthDelivered。 此外,每个salesOrder都有一个ClienTID
现在我想要一个查询列出列中的所有fabricNames。这意味着在我的情况下,所有结构名称都是列标题。在行标题中,将显示所有客户端。针对每个客户,每个结构都有一个值,表示该面料销售给该客户的长度。请尽快帮帮我提前完成。
答案 0 :(得分:-1)
我创建了一个程序来做这个。随意使用它 -
CREATE PROCEDURE do_pivot
@table sysname, -- Name of the table with source data to pivot
@column_field sysname, -- Field used to generate new columns
@value_field sysname = '', -- Values to group within new columns
@order_by sysname = NULL, -- Optional order by field
@function sysname = MAX, -- Optional function to perform on values
@reverse_columns bit = 0 -- If set to 1, reverses order of pivoted columns
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @pivot_fields nvarchar(max);
declare @sql nvarchar(max) = N'
-- Get unique values
set @pivot_fields_OUT = (
select distinct ''['' + CAST(' + @column_field + ' as nvarchar(max)) + ''],''
from ' + @table + '
order by 1 ' + case
when @reverse_columns = 0 then 'asc' else 'desc'
end + '
for xml path('''')
);
-- Remove last comma
set @pivot_fields_OUT = LEFT(@pivot_fields_OUT, LEN(@pivot_fields_OUT) - 1);
';
exec sp_executesql @sql, N'@pivot_fields_OUT nvarchar(max) OUTPUT',
@pivot_fields_OUT=@pivot_fields OUTPUT;
set @sql = N'
select *
from ' + @table + '
pivot (
' + @function + '(' + @value_field + ')
for ' + @column_field + ' in (' + @pivot_fields + ')
) as pvt ' + case
when @order_by is null then ''
else 'order by ' + @order_by
end;
exec(@sql);
END