SQL Summarize和Group

时间:2015-04-28 21:25:48

标签: sql sql-server tsql

我有一张表,我在其中选择以下列

Work_Role
Date_Invoice
Bill_Amnt

我有多个工作角色在多个日期开具发票。我想通过工作角色对此进行总结,并查看每一栏中每年开帐单的金额,仅限2014年和2015年。

这样的事情:

Work_Role     Bill_2014     Bill_2015    
P1            xxx,xxx       xxx,xxx   
P3            xxx,xxx       xxx,xxx    
E1            xxx,xxx       xxx,xxx

3 个答案:

答案 0 :(得分:2)

使用case表达式根据年份有条件地对bill_amnt求和:

select Work_Role, 
    sum(case when year(date_invoice) = 2014 then bill_amnt end) as "Bill_2014",
    sum(case when year(date_invoice) = 2015 then bill_amnt end) as "Bill_2015"
from your_table
group by Work_Role

答案 1 :(得分:1)

使用conditional case expression

select role,
sum(case when year(bill_date) = 2014 then amount else 0 end),
sum(case when year(bill_date) = 2015 then amount else 0 end)
from table
group by role

答案 2 :(得分:0)

您还可以使用PIVOT查询:

SELECT
  WORK_Role,
  COALESCE(Bill_2014,0) AS Bill_2014,
  COALESCE(Bill_2015,0) AS Bill_2015
FROM (
    SELECT
        Work_Role,
        'Bill_'+str(year(Date_Invoice),4) as [year],
        Bill_Amnt as Amount 
    FROM T
) as T
PIVOT
(
    SUM(Amount)
    FOR [year] IN (Bill_2014,Bill_2015)
)AS p;