R
R
Romario212018-06-04 13:31:02
SQL Server
Romario21, 2018-06-04 13:31:02

MS SQL query by grouping?

Hello everyone, please help with the sql query:
CLOSED_ACTIVITY (Closed tasks) within one company there can be many of them. The task is to display not the total number of closed tasks, but to display the number of unique companies that have at least one closed task.
SELECT TOP(1) contact.Id AS ID,contact.Name AS MANAGER,department.Name AS DEPARTMENT,
(SELECT COUNT(Id) FROM Activity WHERE ResultId='632AFDD2-F616-4EA6-87D2-8ED38EED8AFF' AND OwnerId=contact. Id AND ModifiedOn BETWEEN '2018-06-01' AND '2018-06-30') AS CLOSED_ACTIVITY
FROM Contact contact JOIN department ON contact.DepartmentId= department.Id WHERE (DepartmentId ='9b90c192-60e6-df11-971b-001d60e938c6' OR DepartmentId = '66ffa487-b4da-df11-9b2a-001d60e938c6' OR DepartmentId = '2076c4 -df11-971b-001d60e938c6' OR DepartmentId = 'b5f90312-8bc4-415a-ab4f-e311b35bf699') ORDER BY CLOSED_ACTIVITY DESC
This is what is output now:
5b151404ea0da535844835.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
basrach, 2018-06-05
@Romario21

select count(*) as 'кол-во уникальных компаний в которых есть хоть одна закрытая задача'
from Department d
join Contact c on c.DepartmentId = d.Id
where
    d.Id in (
    '9b90c192-60e6-df11-971b-001d60e938c6', 
    '66ffa487-b4da-df11-9b2a-001d60e938c6', 
    '2076c4b6-7fe6-df11-971b-001d60e938c6', 
    'b5f90312-8bc4-415a-ab4f-e311b35bf699')
  and exists(
    select 1 as [closed_activity]
    from Activity a
    where
            a.OwnerId = c.Id
            and a.ModifiedOn between '2018-06-01' and '2018-06-30'
            and a.ResultId = '632AFDD2-F616-4EA6-87D2-8ED38EED8AFF'
  )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question