[英]How do I run this SQL Server query to group by department
如果您希望每個部門有一行,請從 GROUP BY 子句中刪除狀態並使用條件聚合。 這涉及在 COUNT 聚合中使用 case 表達式(或類似表達式)。
select Department,
'In' as [Status In],
count(case Status when 'In' then 1 end) as [Count In],
'Out' as [Status Out],
count(case Status when 'Out' then 1 end) as [Count Out]
from dbo.V_Clean_Data
where Status in ('In', 'Out')
group by Department
order by Department;
嘗試對多個列使用相同的名稱是一個壞習慣。 許多工具不支持這一點。 不知道為什么要在每一行中包含實際狀態值,因為那是非常多余的。
我添加了一些最佳實踐。 模式限定您的表名。 行的順序通常很重要,並且僅由 ORDER BY 子句保證。 使用語句終止符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.