This SQL Server 2005 example demonstrates how to efficiently count distinct program names, grouped by program type and filtered by push number. A previous query only counted all program names, not unique ones.
To accurately count distinct program names, we leverage the COUNT(DISTINCT)
function:
<code class="language-sql">COUNT(DISTINCT <expression>)</code>
This function counts only the unique, non-null values of the specified expression within each group. Here, the expression is program_name
.
The improved query is:
<code class="language-sql">SELECT program_type AS [Type], COUNT(DISTINCT program_name) AS [Count] FROM cm_production WHERE push_number = @push_number GROUP BY program_type;</code>
This query accurately provides a count of unique program names for each program type, given a specific @push_number
. This addresses the original problem of counting distinct values rather than the total number of entries.
The above is the detailed content of How Can I Count Distinct Program Names in SQL Server Using COUNT(DISTINCT)?. For more information, please follow other related articles on the PHP Chinese website!