为Summed Answers创建列

时间:2014-07-01 15:41:16

标签: sql sql-server ssms

所以我试图将我的行信息移到列中 - 我之前没有使用Pivot并尝试使用它但显然我做错了 - 。 - ;

这是我原来的查询

(Select
    CASE WHEN ee.ExpenseTypeID=1 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=2 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=3 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=4 THEN Sum(Amount) END as Amount,
    et.ExpenseDescription,
    ee.UserID
    From ExpensesEntries ee, ExpenseTypes et
    Where ee.ExpenseTypeID=et.ExpenseTypeID
    Group By ee.ExpenseTypeID, et.ExpenseDescription, ee.UserID
    Order By UserID) b

哪种产生类似的东西

Amount    | ExpenseDescription | UserID
----------------------------------------
156.00    | Upload             | 123
----------------------------------------
23.00     | Parking            | 123
----------------------------------------
15.37     | Other              | 123
----------------------------------------
112.00    | Other              | 456
----------------------------------------
28.50     | Parking            | 456
---------------------------------------- 

我想做什么

UserID | Upload | Parking | Other 
----------------------------------
123    | 156.00 | 23.00   | 15.37
----------------------------------
456    | NULL   | 28.50   | 112.00

我试过这样做 - 这相当于拍打Pivot但是我原来的选择中的案例 - 我不确定我是否需要完全摆脱它们并将其添加到Pivot

Select 
    CASE WHEN ee.ExpenseTypeID=1 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=2 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=3 THEN Sum(Amount)
    WHEN ee.ExpenseTypeID=4 THEN Sum(Amount) END as Amount,
    et.ExpenseDescription,
    ee.UserID
    From ExpensesEntries ee, ExpenseTypes et
    Where ee.ExpenseTypeID=et.ExpenseTypeID
    Group By ee.ExpenseTypeID, et.ExpenseDescription, ee.UserID
    Order By UserID
    PIVOT
    (Amount
    FOR et.ExpenseDescription IN ('Upload','Other','Parking')
    ) as pvt

1 个答案:

答案 0 :(得分:0)

您没有提供有关每个ExpenseTypeId值相关内容的详细信息,但您可以使用带有CASE表达式的聚合函数来执行此操作。 CASE表达式将检查ExpenseTypeId的值并获得金额的总和 - 然后您将使用ExpenseDescription命名该列:

select ee.UserId,
    sum(case when ee.ExpenseTypeID=1 then Amount else 0 end) Upload,
    sum(case when ee.ExpenseTypeID=2 then Amount else 0 end) Parking,
    sum(case when ee.ExpenseTypeID=3 then Amount else 0 end) Other
from ExpensesEntries ee
inner join ExpenseTypes et
    on ee.ExpenseTypeID=et.ExpenseTypeID
group by ee.UserId;

如果您想使用PIVOT,那么您可以将查询更改为类似于以下内容。这使用子查询中的2个表之间的连接,并返回UserIdExpenseDescriptionAmount。 PIVOT将汇总每个ExpenseDescription的金额 - 此过程将描述转换为列:

select UserId, Upload, Other, Parking
from
(
    select ee.UserId,
        et.ExpenseDescription 
        Amount
    from ExpensesEntries ee
    inner join ExpenseTypes et
        on ee.ExpenseTypeID=et.ExpenseTypeID
) d
pivot
(
    sum(Amount)
    for ExpenseDescription in (Upload, Other, Parking)
) p;