-1

I need to count distinct date in one column but I do not want to group by that.

Datasource table:

ID   zip5    date       volume  
11   11111   01/03/16   5  
12   11111   01/03/16   6
13   11111   01/04/16   7

My code:

Select zip5, count(ID), count(distinct (date)), sum(volume), 
from table
group by zip5

Desired output:

zip5   count(ID)  count(distinct (date))  sum(volume)
11111          2                       1           11
11111          1                       1            7

However, what I got is:

zip5   count(ID)  count(distinct (date))  sum(volume)
11111          3                       3           18
Michael Li
  • 647
  • 2
  • 8
  • 20

2 Answers2

1

Most likely, the problem you are facing is that your date column has a time component -- and, alas, it is not shown when you select from the table.

You can truncate the date to remove the time component. So try this:

Select zip5, count(ID), count(distinct trunc(date)), sum(volume), 
from table
group by zip5;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Linoff. Thank you very much!. It works. Why the date data format will matter? You mean like minute/second which not show in data? – Michael Li Mar 17 '16 at 13:12
  • @MichaelLi . . . Correct. Oracle does not, by default, show the time component of a `date` column. – Gordon Linoff Mar 18 '16 at 02:42
0

To get your desired output simple add the "DATE" column in the GROUP BY expression.

Select zip5, count(ID), count(distinct ("DATE")), sum(volume)
from "TABLE"
group by zip5,"DATE"
order by 1,2;

      ZIP5  COUNT(ID) COUNT(DISTINCT("DATE")) SUM(VOLUME)
---------- ---------- ----------------------- -----------
     11111          1                       1           7 
     11111          2                       1          11 

You may group by (i.e. select in disctinct rows) even columns that are not in the select list.

Marmite Bomber
  • 19,886
  • 4
  • 26
  • 53