SQL Server - PIVOT分组和排序依据

时间:2017-03-30 02:22:43

标签: sql-server tsql

快速提问,我需要知道如何在SELECT DISTINCT中插入EmployeeID。当我尝试这样插入时:

STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description], lc.EmployeeID)

它给了我一个错误:

  

Msg 145,Level 15,State 1,Line 6   如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

这是整个代码:

DECLARE @LoanTypeDesc AS NVARCHAR(MAX)
SELECT @LoanTypeDesc = STUFF((SELECT DISTINCT ',' + QUOTENAME(lt.[Description]) 
                FROM LoanType lt INNER JOIN LoanContract lc ON lc.LoanTypeID = lt.LoanTypeID
                ORDER BY lc.EmployeeID
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

我想要实现的是我使用PIVOT来获取描述结果并将其设置为列。

这是我的透视代码:

SET @strQuery = 'SELECT *
FROM (
SELECT TOP 1000 EmployeeID,
    LoanAmount,
    lt.LoanTypeID,
    lt.[Description]
FROM LoanContract lc
INNER JOIN LoanType lt ON lt.LoanTypeID = lc.LoanTypeID
ORDER BY EmployeeID ASC
) src
PIVOT(
SUM(LoanAmount)
FOR Description IN (' + @LoanTypeDesc + ')
) piv;'
EXECUTE (@strQuery)

enter image description here

我希望实现这样的目标:

enter image description here

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

只需从枢轴语句中的select中删除lt.LoanTypeID即可。这是因为在pivot语句中有三个部分:分组,聚合和传播。在您的情况下,聚合为LoanAmount,传播为lt.[Description]通过消除检测到分组列。简单地说其余列。因此,结果按EmployeeIDLoanTypeID分组。作为一般规则,您可能希望在大多数情况下为pivot语句选择3列。