1

How to count only once for a specified row even if the row exists more than once?

For instance I have a SQL query

SELECT COUNT(Date) 
FROM mytable 
WHERE name like '%John%'

But it counts all John's number. What I need is, if I find a name John, I want to count only one time, no matter John's name exists more than once.

To illustrate

Name       Date
John       06-09-2012 1am
Robert     06-09-2012 2am
John       06-09-2012 3am 
John       06-09-2012 4am
Robert     06-09-2012 5am

Results should be 1 for John.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
John Smith
  • 2,668
  • 7
  • 30
  • 34

2 Answers2

1

You need to COUNT Distinct Date and also need to use GROUP BY clause like this:

SELECT Name,COUNT(DISTINCT CONVERT(varchar,date,103)) AS NameCount
FROM mytable WHERE name LIKE '%John%'
GROUP BY name

SEE THIS FIDDLE for name LIKE '%John%'.

Also, for each user try this:

SELECT Name,COUNT(DISTINCT CONVERT(varchar,date,103)) AS NameCount
FROM mytable GROUP BY name

SEE THIS FIDDLE for Each user.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
-1

Update query as per clear requirements

For oracle

SELECT count(distinct (extract day from date)) FROM mytable WHERE name like '%John%' and Date is not null;

Kamal
  • 5,462
  • 8
  • 45
  • 58
  • Thanks, What about count each name for each day. The results should be 1 for 06-09-2012 with name=john, and 1 for 07-09-2012 with name=john. So, for each day john should be counted. How can I do that ? – John Smith Aug 09 '12 at 06:35
  • @JohnSmith [See this answer](http://stackoverflow.com/questions/11877717/how-to-count-only-once-for-a-specified-record/11877846#11877846) again. This is exactly what you want. – Himanshu Aug 09 '12 at 06:37
  • Sorry I did not you question first time, answer by @hims056 will solve your problem – Kamal Aug 09 '12 at 06:52