在我的查询下。我选择这种方式按姓名计算所有工作。
SELECT COUNT(sy.FullName) [Count Job],
sy.FullName [FullName],
MIN(CAST(i.vrp_notificationdate AS DATE)) [Oldest Date]
FROM BusinessUnit AS b
INNER JOIN SystemUser AS sy
ON b.BusinessUnitId = sy.BusinessUnitId
INNER JOIN Incident AS i
ON i.OwnerId = sy.SystemUserId
GROUP BY f.sy.FullName
此查询显示此表
--------------------------------- Count Job FullName Oldest Date 10 a 2011-10-11 20 B 2011-10-11 55 C 2011-10-11 ---------------------------------
但我想以下表为例。
-------------------------------------------------------------- Count Job FullName Oldest Date Open Job Close Job 10 A 2011-10-11 5 5 20 B 2011-10-11 13 7 55 C 2011-10-11 48 7 ------------------------------------------------------------
我的事件表上有columnname的状态,如果状态代码是5,则作业被关闭。当我按条件状态代码使用group,然后table就在。我不想显示这个显示表。
--------------------------------- Count Job FullName Oldest Date 10 a 2011-10-11 13 B 2011-10-11 48 C 2011-10-11 7 B 2011-10-11 7 C 2011-10-11 ---------------------------------
当我在我的t-sql上使用union时,我接受此错误“使用UNION,INTERSECT或EXCEPT运算符组合的所有查询必须在其目标列表中具有相同数量的表达式。”
如何准确解决此问题。任何建议。
感谢。
答案 0 :(得分:2)
如何使用CASE和SUM?
SELECT COUNT(sy.FullName) [Count Job],
sy.FullName [FullName],
MIN(CAST(i.vrp_notificationdate AS DATE)) [Oldest Date],
SUM(CASE i.status
WHEN 5 THEN 1
ELSE 0) [Open Jobs],
SUM(CASE i.status
WHEN 5 THEN 0
ELSE 1) [Closed Jobs]
FROM BusinessUnit AS b
INNER JOIN SystemUser AS sy
ON b.BusinessUnitId = sy.BusinessUnitId
INNER JOIN Incident AS i
ON i.OwnerId = sy.SystemUserId
GROUP BY f.sy.FullName