对 SQL 中的每一列求和并显示在行中

Sum each column in SQL and show them in Row

我有一个 table 'task' 如下

其中 ID 是唯一记录,deptA.....deptD 是部门。 1表示完成,0表示未完成。 我想计算每个部门的总和如下

我想像下面那样做,但我不知道如何转置到行

select Sum(deptA) as deptA, 
       Sum(deptB) as deptB, 
       Sum(deptC) as deptC, 
       Sum(deptD) as deptD, 
       count(*) as total 
  from task

注意 - 无法使用 pivot/unpivot 功能,因为我的应用程序不支持它。

您可以使用 cross apply 进行反透视,然后聚合:

select x.dept, sum(x.status) complete, sum(1 - x.status) incomplete
from task t
cross apply (values 
    ('deptA', deptA), ('deptB', deptB), ('deptC', deptC), ('deptD', deptD)
) x(dept, status)
group by x.dept

这假定部门列中只有 0/1 个值,这简化了聚合逻辑。

一个选项是 Conditional AggregationUNION ALL,以便根据需要对数据进行逆透视:

SELECT 'DeptA' AS "Depatments", SUM(CASE WHEN deptA= 1 THEN 1 ELSE 0 END) AS "Completed", SUM(CASE WHEN deptA= 0 THEN 1 ELSE 0 END) AS "Incomplete"
  FROM task
UNION ALL
SELECT 'DeptB', SUM(CASE WHEN deptB= 1 THEN 1 ELSE 0 END), SUM(CASE WHEN deptB= 0 THEN 1 ELSE 0 END)
  FROM task
UNION ALL
SELECT 'DeptC', SUM(CASE WHEN deptC= 1 THEN 1 ELSE 0 END), SUM(CASE WHEN deptC= 0 THEN 1 ELSE 0 END) 
  FROM task
UNION ALL
SELECT 'DeptD', SUM(CASE WHEN deptD= 1 THEN 1 ELSE 0 END), SUM(CASE WHEN deptD= 0 THEN 1 ELSE 0 END) 
  FROM task