TSQL PIVOT [年],COUNT(SalesPeople)和GROUP BY [Territory]

时间:2018-04-07 21:15:15

标签: sql-server tsql count pivot grouping

在AdventureWorks数据库中,我试图按地区返回每年的总销售额,并包括每个地区有多少销售人员活跃。以下代码无法按地区分组,而是为每个销售人员创建唯一行。我的代码丢失了什么?

期望的结果

| SalesTerritory | SalesPeople | 2011   | 2012    | 2013    | 2014    |
+----------------+-------------+--------+---------+---------+---------+
| Australia      | 1           | NULL   | NULL    | 184105  | 1237705 |
| Canada         | 2           | 115360 | 3426082 | 2568323 | etc...  |

代码

SELECT
     pvt.SalesTerritory
    ,COUNT(pvt.SalesPersonID) AS SalesPeople
    ,pvt.[2011]
    ,pvt.[2012]
    ,pvt.[2013]
    ,pvt.[2014]
FROM    (SELECT
            st.[Name] AS [SalesTerritory]
            ,soh.[SalesPersonID]
            ,soh.[SubTotal]
            ,YEAR(DATEADD(m, 6, soh.[OrderDate])) AS [FiscalYear]
         FROM   [Sales].[SalesPerson] sp
            INNER JOIN  [Sales].[SalesOrderHeader] soh
                ON sp.[BusinessEntityID] = soh.[SalesPersonID]
            INNER JOIN  [Sales].[SalesTerritory] st
                ON sp.[TerritoryID] = st.[TerritoryID]
            INNER JOIN  [HumanResources].[Employee] e
                ON soh.[SalesPersonID] = e.[BusinessEntityID]
            INNER JOIN  [Person].[Person] p
                ON p.[BusinessEntityID] = sp.[BusinessEntityID]) AS soh
PIVOT
    (
    SUM([SubTotal]) FOR [FiscalYear] IN ([2011], [2012], [2013], [2014])
    ) AS pvt
GROUP BY    pvt.SalesTerritory
            ,[2011]
            ,[2012]
            ,[2013]
            ,[2014];

实际结果

| SalesTerritory | SalesPeople | 2011   | 2012    | 2013    | 2014    |
+----------------+-------------+--------+---------+---------+---------+
| Australia      | 1           | NULL   | NULL    | 184105  | 1237705 |
| Canada         | 1           | 9109   | 1254087 | 1179530 | 1166720 |
| Canada         | 1           | 106251 | 2171995 | 1388793 | etc...  |

1 个答案:

答案 0 :(得分:1)

您应该仅将SalesTerritory中最上面的查询和组中的小计相加。

见下文

SELECT
     pvt.SalesTerritory
    ,COUNT(pvt.SalesPersonID) AS SalesPeople
    ,sum(pvt.[2011])
    ,sum(pvt.[2012])
    ,sum(pvt.[2013])
    ,sum(pvt.[2014])
FROM    (SELECT
            st.[Name] AS [SalesTerritory]
            ,soh.[SalesPersonID]
            ,soh.[SubTotal]
            ,YEAR(DATEADD(m, 6, soh.[OrderDate])) AS [FiscalYear]
         FROM   [Sales].[SalesPerson] sp
            INNER JOIN  [Sales].[SalesOrderHeader] soh
                ON sp.[BusinessEntityID] = soh.[SalesPersonID]
            INNER JOIN  [Sales].[SalesTerritory] st
                ON sp.[TerritoryID] = st.[TerritoryID]
            INNER JOIN  [HumanResources].[Employee] e
                ON soh.[SalesPersonID] = e.[BusinessEntityID]
            INNER JOIN  [Person].[Person] p
                ON p.[BusinessEntityID] = sp.[BusinessEntityID]) AS soh
PIVOT
    (
    SUM([SubTotal]) FOR [FiscalYear] IN ([2011], [2012], [2013], [2014])
    ) AS pvt
GROUP BY    pvt.SalesTerritory