簡體   English   中英

如何基於SQL Server中一列的值對行進行分組和獲取計數

[英]How to group and get count of rows based on value of one column in sql server

我有一個帶有列RequestType,status的請求表。Status列的值可以在進行中,進行組合等。我想獲取類似的列表

RequestType  In-Progress  Completed    Total 
Type1         10          5            15
Type2         10          10           20

我嘗試通過使用2列(RequestType,status)對group進行嘗試,但它沒有給出確切的結果。

請幫助我的SQL查詢。

預先感謝Subin

一種方法是使用條件農業:

SELECT RequestType,
       SUM(CASE WHEN Status = 'In-Progress' THEN 1 ELSE 0 END) As 'In-Progress',
       SUM(CASE WHEN Status = 'Completed' THEN 1 ELSE 0 END) As 'Completed',
       COUNT(Status) As 'Total'
FROM TableName
WHERE Status IN('In-Progress', 'Completed')
GROUP BY RequestType

使用PIVOT

select *, [In-Progress]+[Completed] total
from TableName
pivot ( count(status) for status in ([In-Progress], [Completed])) as p

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM