views:

1040

answers:

5

I have a query where I want to get distinct dates, the phone numbers associated with those dates, and a count of the phone numbers per date.

For example, I have a database with dates and phone numbers and I want the result to be

9/2005      5554446666    3
9/2005      4445556666    1
10/2005     1112223333    1
11/2005     2223334444    2

I can get the dates and the counts with this query:

SELECT DISTINCT date, count(phone) AS count
FROM calls
GROUP BY date

What I can't seem to get is the phone number the 'count' is counting. I think I need some sort of aggregate function to get a single instance of the list of unique values but First() and a few others only throw a SQL error. Do I need a subquery?

+2  A: 

That's because you're grouping by date not by phone.

In one grouping of a date there may be three different numbers and it's impossible for SQL to know which one you want.

joshcomley
+7  A: 
SELECT date, PhoneNumber, count(phone) AS count
    FROM calls
    GROUP BY date, PhoneNumber

should do it I think

Tetraneutron
+4  A: 

You may want to try something like

SELECT Date, Phone, Count(*) As Count From Calls GROUP BY Date, Phone

This will give you a tally of each phone number on each date, with how many times that number appeared on that date.

Kibbee
A: 
SELECT date, phone, count(phone) AS count FROM calls GROUP BY date, phone

(You don't need DISTINCT with a GROUP BY.)

Stuart Dunkeld
+1  A: 
SELECT Date, Phone, Count(Phone) As Count From Calls GROUP BY Date, Phone

this query gets me a list of all the records, and I get a duplicates of the phone numbers and dates with a count of how often the phone number shows up for that date. How can I make it so that I get a distinct set for phone numbers and dates with the count of how many times that number shows up for that date?

I think you need to extract just the date part of the "Date" in SQL server you can do something like convert(varchar(10), Date, 101) to extract just the date portion - You'll need to group on this to ensure you don't get what appear to be duplicates but are actually unique based on the time part of teh date.
Tetraneutron
I am, actually.I tried to keep it simple to avoid confusion, but it looks like:SELECT CONVERT(varchar(7), date,20) AS date, COUNT(phone) as count<br>FROM Calls<br>GROUP BY date
For SQL Server, change the statement to be: select convert(varchar(10), date, 101) as Date, phone, count(phone) as Count from calls group by convert(varchar(10), date, 101), phoneNote that the GROUP BY has to be converted too, otherwise it's grouping by the source values.
Marshall Fryman
That was the ticket! Thanks!