我有以下查询:
select distinct
(SELECT COUNT (TaskID) FROM Task, Employee where SupervisorID = '752A0F4D-9905-4D55-87F1-AFA19245C206' and task.UserID = Employee.UserID) as Total,
(SELECT COUNT (TaskID) FROM Task, Employee where SupervisorID = '752A0F4D-9905-4D55-87F1-AFA19245C206' and task.UserID = Employee.UserID and DateDue <= DATEADD(day,-1, GETDATE()) )as TotalOverdue,
(SELECT COUNT (TaskID) FROM Task, Employee where SupervisorID = '752A0F4D-9905-4D55-87F1-AFA19245C206' and task.UserID = Employee.UserID and DateDue >= DATEADD(day,-1, GETDATE()) ) as Totaldue
from Task
它给了我以下结果:
Total | TotalOverdue | TotalDue
5 | 4 | 1
但是,我希望它以这种方式形成:
Total: 5
TotalOverdue: 4
TotalDue: 1
我尝试过使用pivot功能,但是无法让它正常工作。有什么想法吗?
答案 0 :(得分:0)
我认为你可以通过条件聚合做你想做的事情:
select count(*) as Total,
sum(case when DateDue <= DATEADD(day, -1, GETDATE()) then 1 else 0
end) as TotalOverdue,
sum(case when DateDue >= DATEADD(day, -1, GETDATE()) then 1 else 0
end) as TotalDue
from Task join
Employee
on task.UserID = Employee.UserID
where SupervisorID = '752A0F4D-9905-4D55-87F1-AFA19245C206';
如果你想要所有的主管,
select SupervisorID, count(*) as Total,
sum(case when DateDue <= DATEADD(day, -1, GETDATE()) then 1 else 0
end) as TotalOverdue,
sum(case when DateDue >= DATEADD(day, -1, GETDATE()) then 1 else 0
end) as TotalDue
from Task join
Employee
on task.UserID = Employee.UserID;
编辑:
你真的想要取消数据的转移。这是一种方法:
select n.which,
(case when n.which = 'Total'
then count(*)
when n.which = 'TotalOverdue'
then sum(case when DateDue <= DATEADD(day, -1, GETDATE()) then 1 else 0
end)
else sum(case when DateDue >= DATEADD(day, -1, GETDATE()) then 1 else 0
end)
end) as value
from Task join
Employee
on task.UserID = Employee.UserID cross join
(select 'Total' as which union all 'TotalOverdue' union all 'TotalDue') n
group by n.which;
如果您想要一个字符串列,请使用concat()
。