In SQL Server 2005 I have a table cm_production
that lists all the code that's been put into production. The table has a ticket_number
, program_type
, program_name
and push_number
along with some other columns.
GOAL: Count all the DISTINCT program names by program type and push number.
What I have so far is:
DECLARE @push_number INT;
SET @push_number = [HERE_ADD_NUMBER];
SELECT DISTINCT COUNT(*) AS Count, program_type AS [Type]
FROM cm_production
WHERE push_number=@push_number
GROUP BY program_type
This gets me partway there, but it's counting all the program names, not the distinct ones (which I don't expect it to do in that query). I guess I just can't wrap my head around how to tell it to count only the distinct program names without selecting them. Or something.
8条答案
按热度按时间wswtfjt71#
Count all the DISTINCT program names by program type and push number
DISTINCT COUNT(*)
will return a row for each unique count. What you want isCOUNT(DISTINCT <expression>)
: evaluates expression for each row in a group and returns the number of unique, non-null values.cfh9epnr2#
I needed to get the number of occurrences of each distinct value. The column contained Region info. The simple SQL query I ended up with was:
Which would give me a list like, say:
6ju8rftf3#
You have to create a derived table for the distinct columns and then query the count from that table:
Here
dt
is a derived table.rsaldnfx4#
at0kjp5o5#
try this:
yyyllmsg6#
You can try the following query.
vql8enpb7#
To count distinct program names by program type and push number in SQL Server 2005, you can use a subquery to first select the distinct program names, and then perform the count in the outer query. Here's an example query that should give you the desired result:
In this query, the subquery selects the distinct program names and program types from the cm_production table based on the specified push_number. Then, in the outer query, you perform the count on the distinct program names and group the results by program type.
By the way, with dbForge Studio for SQL Server , you can easily write, execute, and analyze your SQL queries.
hec6srdp8#
This is a good example where you want to get count of Pincode which stored in the last of address field