将行转换为列为Uknown mumber列

时间:2016-06-24 19:49:33

标签: sql-server sql-server-2008 tsql

我需要将行转置为列,但我不知道表格中的行数。此示例适用于静态行数。我在这个网站上发现了几个动态SQL示例,但我不清楚它们是如何工作的,这就是我需要的。



SELECT [9 payments], [Delay Tax return], [New Payment Schedule]
FROM
(SELECT RehabMetric, Reviews.ReviewID
FROM RehabMetricsCalls INNER JOIN
     RehabMetrics ON RehabMetricsCalls.RehabMetricID = RehabMetrics.RehabMetricID INNER JOIN
     Reviews ON RehabMetricsCalls.ReviewID = Reviews.ReviewID) AS pivTemp
PIVOT
(   COUNT(ReviewID)
    FOR RehabMetric IN ([9 payments], [Delay Tax return], [New Payment Schedule])
) AS pivTable

Table names:

*RehabMetrics*
RehabMetricID
RehabMetric

(Sample Data)
2, Nine Payments
7,Delay Tax Return
12, Continue Payments

*RehabMetricsCalls*
RehabMetricID
ReviewID

*Reviews*
ReviewID




1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,那么您需要替换查询的这一部分

select name from some_table_with_your_column_names

通过动态的东西。

假设有一个查询返回您的列名,例如

name
---------------------
[9 payments]
[Delay Tax return]
[Delay Tax return]

你的案例中的结果是

declare @columns nvarchar(max) = '';

select @columns = concat(@columns, iif(@columns <> '', '], ', ''), '[', name) 
from some_table_with_your_column_names
where name is not null
and name <> '';

if @columns <> '' begin
    select @columns = concat(@columns, ']');

    declare @query nvarchar(max) = N'select ' + @columns + ' from ( select RehabMetric, Reviews.ReviewID from RehabMetricsCalls inner join RehabMetrics ON RehabMetricsCalls.RehabMetricID = RehabMetrics.RehabMetricID inner join Reviews ON RehabMetricsCalls.ReviewID = Reviews.ReviewID) AS pivTemp pivot(  count(ReviewID) for RehabMetric in (' + @columns + ')) AS pivTable';

    execute sp_executesql @query;
end else begin
    -- do something else here if your column list is empty
end 

现在让我们试着回答你的问题

<asp:GridView ID="gridview1" runat="server" >
    <asp:TemplateField>
        <ItemTemplate>
            <asp:GridView ID="gridview2" runat="server" >
                <Columns>

                </Columns>
            </asp:GridView>
        </ItemTemplate>
    </asp:TemplateField>
</asp:GridView>