SQL / TSQL:在多个表上使用PIVOT

时间:2014-11-25 20:36:15

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

我试图用SQL中的PIVOT解决两个类似的问题。我有三张桌子:

  • 第一个有列:orderid,empid,orderdate;
  • 第二列:orderid,productid,unitprice
  • 第三个包含列:empid,firstname,lastname等(有关工人的其他信息)

现在,我需要使用PIVOT来管理这样的事情:

empid firstname lastname 2006 2007 2008
1     aaa       bbb      1    55    77
1     aaa       bbb      2    58    79
2     xxx       ccc      4    59    82
....................................... 

2006年,2007年,2008年的数字列是每年分配的订单。

我有这样的事情(Pivott内部的查询工作正常):

WITH Pivott AS
(
    SELECT
        so.empid, 
        YEAR(so.orderdate),
        so.orderid,
        hr.lastname,
        hr.firstname
    FROM 
        Sales.Orders so
    LEFT OUTER JOIN
        HR.Employees hr ON so.empid = hr.empid
)
SELECT 
    YEAR(orderdate), [2006], [2007], [2008]
FROM 
    Pivott
PIVOT
    (SUM(orderid) FOR YEAR(orderdate) IN [2006], [2007], [2008]) AS PIV;

第二个问题:

我尝试使用PIVOT来管理这样的事情:

empid firstname lastname 2006  2007  2008
1     aaa       bbb      453   34    77
2     vvv       kkk      345   89    123
3     xxx       ccc      453   12    82
....................................... 

2006,2007,2008栏中的数字是指特定年份工人(empid)执行的订单的所有价格的总和。

我有这个:

WITH Pivott AS
(
    SELECT
        so.empid,
        YEAR(so.orderdate) AS YEAR,
        so.orderid AS ORDERS,
        hr.lastname,
        hr.firstname,
        s.unitprice AS SUMA
    FROM 
        Sales.Orders so
    LEFT OUTER JOIN
        HR.Employees hr ON so.empid = hr.empid
    INNER JOIN
        Sales.OrderDetails s ON so.orderid = s.orderid
)
SELECT 
    YEAR(orderdate), [2006], [2007], [2008]
FROM 
    Pivott
PIVOT
    (SUM(unitprice) FOR YEAR(orderdate) IN ([2006], [2007], [2008])) AS PIV;

我需要改变什么来实现我想要的输出?

感谢您的时间!

1 个答案:

答案 0 :(得分:2)

您似乎正在尝试对CTE应用Pivot命令

试试这个;

;WITH pvtCTE AS
(SELECT so.empid,
YEAR(so.orderdate) AS SalesYEAR,
--so.orderid AS ORDERS, /** removed from grouping**/
hr.lastname,
hr.firstname,
SUM(ISNULL(s.unitprice,0.00)) as unitprice /** pre grouping adjusted per comment**/
FROM Sales.Orders so
left outer join HR.Employees hr on so.empid = hr.empid
inner join Sales.OrderDetails s on so.orderid = s.orderid
GROUP BY so.empid, YEAR(so,orderDate), hr.lastname, hr.firstname --added for aggregated CTE results
)

SELECT empid, firstname, lastname, [2006], [2007], [2008]
FROM (SELECT * FROM pvtCTE) p
PIVOT (
SUM(unitprice)
FOR SalesYEAR IN ([2006],[2007],[2008])
) as pvt;