【问题标题】:I need to query a single table multiple times and show the results in a single result set我需要多次查询单个表并在单个结果集中显示结果
【发布时间】:2020-10-28 10:01:11
【问题描述】:

我需要多次查询单个表并将结果显示在单个结果集中。以下是表格示例。

Period | Employer    | Hours
SEP20  | Emp1        | 5
SEP20  | Emp1        | 10
OCT20  | Emp2        | 10
SEP20  | Emp2        | 10
SEP20  | Emp3        | 10

我想汇总小时数并显示如下结果,我还需要一个列来汇总所有雇主的小时数,但 Emp1 除外。

Period| Emp1      | Emp2     | Emp3    | Allexcept Emp1
SEP20 | 15        | 10       | 10      | 20
OCT20 | 10        | NULL     | NULL    |  NULL

我正在寻找最有效的查询。非常感谢

【问题讨论】:

标签: sql sql-server tsql sum pivot


【解决方案1】:

对于员工的修复列表,您可以进行条件聚合:

select period,
    sum(case when employer =  'Emp1' then hours end) emp1,
    sum(case when employer =  'Emp2' then hours end) emp2,
    sum(case when employer =  'Emp3' then hours end) emp3,
    sum(case when employer <> 'Emp1' then hours end) all_but_emp1
from mytable
group by period

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 2010-10-15
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多