在SQL列中統計條件值
假設您有一個名為「Priority」的列,其中包含1到5之間的整數值。您希望產生一個圖表來顯示每個優先值的計數。例如,「Priority1」應統計「Priority」值為1的行數,「Priority2」應統計「Priority」值為2的行數,以此類推。
解:
為此,您可以使用帶有條件聚合函數的SQL查詢:
<code class="language-sql">SELECT jobID, JobName, SUM(CASE WHEN Priority = 1 THEN 1 ELSE 0 END) AS priority1, SUM(CASE WHEN Priority = 2 THEN 1 ELSE 0 END) AS priority2, SUM(CASE WHEN Priority = 3 THEN 1 ELSE 0 END) AS priority3, SUM(CASE WHEN Priority = 4 THEN 1 ELSE 0 END) AS priority4, SUM(CASE WHEN Priority = 5 THEN 1 ELSE 0 END) AS priority5 FROM Jobs GROUP BY jobID, JobName;</code>
此查詢使用條件聚合來計算每個優先權值的行的數量。 CASE表達式檢查Priority的值,如果它與所需的優先權值匹配,則傳回1,否則傳回0。然後,SUM函數會累積這些值以產生最終計數。
如果您不需要結果中的jobID和JobName欄位,可以將它們從SELECT子句中刪除,並刪除GROUP BY子句:
<code class="language-sql">SELECT SUM(CASE WHEN Priority = 1 THEN 1 ELSE 0 END) AS priority1, SUM(CASE WHEN Priority = 2 THEN 1 ELSE 0 END) AS priority2, SUM(CASE WHEN Priority = 3 THEN 1 ELSE 0 END) AS priority3, SUM(CASE WHEN Priority = 4 THEN 1 ELSE 0 END) AS priority4, SUM(CASE WHEN Priority = 5 THEN 1 ELSE 0 END) AS priority5 FROM Jobs;</code>
以上是如何計算 SQL 列中的條件值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!