我该如何解决此数据透视声明

时间:2019-01-08 11:08:19

标签: sql-server tsql pivot pivot-table

旋转该表时出现此错误。

错误

  

“ Properties.userAccount.accountUsername”列在   选择列表,因为它既不包含在任何聚合中   函数或GROUP BY子句。

2 个答案:

答案 0 :(得分:0)

我会这样做:

SELECT uac.accountUsername,
       SUM(CASE WHEN YEAR(prop.soldDate) = 2017 THEN 1 ELSE 0 END) AS [2017],
       SUM(CASE WHEN YEAR(prop.soldDate) = 2018 THEN 1 ELSE 0 END) AS [2018]
FROM [Properties].[userAccount] uac JOIN 
     [Properties].[property] prop
     ON uac.accountId = prop.accountId
GROUP BY uac.accountUsername;

对于您的PIVOT版本,您只是想在GROUP BY子句中包含未聚合的列,即uac.accountUsername, YEAR(prop.soldDate)

因此应包括在内:

WITH AnnualSales (Username, YearOfSale, Properties) AS (
     SELECT uac.accountUsername, YEAR(prop.soldDate), COUNT(prop.propertyId)
     FROM [Properties].[userAccount] uac JOIN 
           [Properties].[property] prop
           ON (uac.accountId = prop.accountId)
     GROUP BY uac.accountUsername, YEAR(prop.soldDate)
)
SELECT *
FROM AnnualSales PIVOT 
    (SUM(Properties) FOR YearOfSale IN ([2017],[2018])
    ) AS pvt
ORDER BY 1 ASC;

答案 1 :(得分:0)

您的PIVOT语法已关闭:

SELECT
    accountUsername,
    year,
    [2017],
    [2018]
FROM
(
    SELECT uac.accountUsername, YEAR(prop.soldDate) AS year
    FROM [Properties].[userAccount] uac
    INNER JOIN [Properties].[property] prop
        ON uac.accountId = prop.accountId
) t
PIVOT (COUNT(*) FOR YearOfSale IN ([2017],[2018])) AS pvt
ORDER BY 1;