字段未修复时使用数据透视的SQL查询

时间:2016-08-23 06:06:47

标签: sql-server database stored-procedures sql-server-2012

在SQL中使用数据透视功能之前我得到了这个记录结构

enter image description here

使用Pivot后:

enter image description here

这是我的SQL查询

SELECT

            FromHubID,
            FromHubName,
            ToHubID,
            SUM([1 - 100]) AS [1 - 100],
            SUM([101 - 250]) AS [101 - 250],
            SUM([251 - 500]) AS [251 - 500],
            SUM([501 - 1000]) AS [501 - 1000]

            FROM
    (SELECT 
            AccountGroupID,
            FromHubID,
            FromHubName,
            ToHubID,
            T_ID,
            [1 - 100],
            [101 - 250],
            [251 - 500],
            [501 - 1000]
    FROM
    (
        SELECT 
              AG.AccountGroupID
             ,AG.FromHubID
             ,FH.Hub_Name AS FromHubName
             ,AG.ToHubID
             ,AG.T_ID
             ,CONVERT(VARCHAR , [MinWeight])  + ' - ' + CONVERT(VARCHAR ,[MaxWeight]) AS slot
             ,[Rate]

          FROM 
                [CourierDev].[dbo].[AccountGroupQuotation] AS AG
                INNER JOIN HubMaster AS FH ON FH.Hub_Id = AG.FromHubID
          WHERE
                 accountgroupid = 1

    )Sourcetable

    PIVOT
    (
           Sum(Rate)          
           FOR slot IN (  [1 - 100],
                        [101 - 250],
                        [251 - 500],
                        [501 - 1000] )
    )AS AGQuotationList 
    )AS tbl

     GROUP  BY 
            FromHubID,
            FromHubName,
            ToHubID

我的问题是插槽中的字段数和它的值不在这里修复我在数据库语法中添加静态字段并选择语法 对于这个特定的记录,但是如何管理插槽的值和插槽值的计数何时不能解决?

FOR示例 如果只有2种类型的记录[1 - 100],[101 - 250]那么我只需要两个支点

1 个答案:

答案 0 :(得分:1)

您可以使用动态SQL:

DECLARE @columns nvarchar(max),
        @sql nvarchar(max)

SELECT @columns = COALESCE(@columns,'') +','+QUOTENAME(slot)
FROM #YourTable
GROUP BY slot

SELECT @sql = N'
SELECT  FromHubID,
        FromHubName,
        ToHubID
        '+@columns+'
FROM #YourTable
PIVOT (
    SUM(Rate) FOR slot IN ('+STUFF(@columns,1,1,'')+')
) as pvt'

EXEC sp_executesql @sql

输出:

FromHubID   FromHubName     ToHubID 1 - 100 101 - 250   251 - 500   501 - 1000
5           BARODA R. O.    1       1       2           3           4
5           BARODA R. O.    5       5       6           7           8