Home >Database >Mysql Tutorial >How Can I Count Distinct Program Names in SQL Server Using COUNT(DISTINCT)?

How Can I Count Distinct Program Names in SQL Server Using COUNT(DISTINCT)?

DDD
DDDOriginal
2025-01-14 19:07:48369browse

How to Count Unique Program Names in SQL Server with COUNT(DISTINCT)

Counting Unique Program Names Using COUNT(DISTINCT) in SQL Server

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn