簡體   English   中英

MYSQL:在單個查詢中計算按兩個不同條件分組的列的 SUM

[英]MYSQL: Calculate the SUM of a column grouped by two different conditions in a single query

假設我有這些示例數據的簡化表結構:

id | duration_seconds (int) | is_billable (boolean)
1  | 100                    | false
2  | 500                    | true
3  | 100                    | false
4  | 150                    | true

是否可以從單個查詢中獲得這樣的結果?

total_duration | billable_duration | non_billable_duration
850            | 650               | 200

您可以使用條件聚合在一個查詢中獲取不同的總和:

SELECT SUM(duration_seconds ) AS total_duration,
       SUM(CASE WHEN is_billable THEN duration_seconds ELSE 0 END) AS billable_duration,
       SUM(CASE WHEN NOT is_billable THEN duration_seconds ELSE 0 END) AS non_billable_duration
FROM yourtable

輸出(對於您的樣本數據)

total_duration  billable_duration   non_billable_duration
850             650                 200

SQLFiddle 上的演示

暫無
暫無

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

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