Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add column which count distinct person any city

I have the table like this:

Person    City    workingdate
A    Newyork    10.11.2015
A    Newyork    11.11.2015
A    Newyork    12.11.2015
B    Newyork    10.11.2015
B    Newyork    15.11.2015
B    Newyork    16.11.2015
B    Newyork    18.11.2015

I want to have a column which count distinct person within city:

Person    City    workingdate  countdistinctpersonincity
A    Newyork    10.11.2015             1
A    Newyork    11.11.2015             0
A    Newyork    12.11.2015             0
B    Newyork    10.11.2015             1
B    Newyork    15.11.2015             0
B    Newyork    16.11.2015             0
B    Newyork    18.11.2015             0

Can you please help me how to do that?

CREATE TABLE Persons
(Person varchar(25),
City varchar(255),
workingdate varchar(10));

insert into Persons
values ('A', 'Newyork','10.11.2015'),
('A', 'Newyork','11.11.2015'),
('A', 'Newyork','12.11.2015'),
('B', 'Newyork','10.11.2015'),
('B', 'Newyork','15.11.2015'),
('B', 'Newyork','16.11.2015'),
('B', 'Newyork','18.11.2015');
like image 255
phalondon Avatar asked Dec 22 '16 11:12

phalondon


1 Answers

One variant:

SELECT *
      ,IIF(ROW_NUMBER() OVER(PARTITION BY City, Person ORDER BY workingdate) = 1, 1, 0)
FROM Persons

enter image description here


For SQL Server before 2012, you can use:

SELECT P.*
      ,CASE WHEN DS.[City] IS NULL THEN 0 ELSE 1 END
FROM Persons P
LEFT JOIN 
(
    SELECT City
          ,Person
          ,MIN(workingdate) AS workingdate
    FROM Persons
    GROUP BY City
            ,Person
) DS
    ON P.City = DS.[City]
    AND P.[Person] = DS.[Person]
    AND P.[workingdate] = DS.[workingdate]
like image 197
gotqn Avatar answered Oct 11 '22 18:10

gotqn