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');
One variant:
SELECT *
,IIF(ROW_NUMBER() OVER(PARTITION BY City, Person ORDER BY workingdate) = 1, 1, 0)
FROM Persons
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With