1

I need to a distinct number of values in a column and group it by date, The real problem is the count should not include if it already occurred in a previous result.

Eg: Consider the table tblcust

 Date        Customers
 March 1     Mike
 March 1     Yusuf
 March 1     John
 March 2     Ajay
 March 2     Mike
 March 2     Anna

The result should be

Date       Customer_count
March 1       3
March 2       2

If I use

select date,count(distinct(customer)) as customer_count
group by date

The Result I am getting is

Date      customer_count    
March 1   3
March 2   3

The customer, Mike has been visited twice, It should not be counted as a new customer.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42

1 Answers1

0

You can try and achieve this using SQL Server ROW_NUMBER Function .

create table tblCust (DtDate varchar(20), Customers Varchar(20))
insert into tblCust Values
('March 1', 'Mike'),
('March 1', 'Yusuf'),
('March 1', 'John'),
('March 2', 'Ajay'),
('March 2', 'Mike'),
('March 2', 'Anna')

 Select dtDate
     , Customers
     , ROW_NUMBER() OVER (PARTITION BY Customers ORDER BY DtDate) as SrNo
from tblCust
order by DtDate, SrNo

select Dtdate,
    count(distinct(customers)) as customer_count
from(Select dtDate
     , Customers
     , ROW_NUMBER() OVER (PARTITION BY Customers ORDER BY DtDate) as SrNo
from tblCust
)a where SrNo = 1
group by Dtdate

Here is the live db<>fiddle demo

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42