这是我的初步查询:
select
CASE WHEN a.TO_WG_ID is null
and a.CREATED_DATE_TIME =
(select min(b.created_date_time) from ymtn.message b
where b.thread_id = a.thread_id) THEN 1 ELSE 0
END AS "Created"
from ymtn.MESSAGE a
left join YMTN.WORKGROUP b
ON a.FROM_WG_ID=b.WORKGROUP_ID
where b.WORKGROUP_ID='1STOP_PROCESS'
它给了我一列一堆1'和0' s。我想要的只是总和..只是一个数字,例如如果我在case语句前面放了一个SUM,我会收到这个错误: 消息130,级别15,状态1,行5 无法对包含聚合或子查询的表达式执行聚合函数。那么我该怎么做?我使用了这个查询:
select count(CREATED_DATE_TIME) as 'Created'
from ymtn.MESSAGE a
LEFT JOIN YMTN.WORKGROUP b
ON a.FROM_WG_ID=b.WORKGROUP_ID
where CREATED_DATE_TIME=(SELECT MIN(b.CREATED_DATE_TIME) FROM YMTN.MESSAGE b WHERE
b.THREAD_ID = a.THREAD_ID)
and a.TO_WG_ID is null
and b.WORKGROUP_ID='1STOP_PROCESS'
但是我希望它在case语句中工作,而不必将嵌套的select向下移动到WHERE子句。
答案 0 :(得分:1)
你可以将整个事物扔进子查询并总结一下吗?
select sum(Created)
from (
select
CASE WHEN a.TO_WG_ID is null
and a.CREATED_DATE_TIME =
(select min(b.created_date_time) from ymtn.message b
where b.thread_id = a.thread_id) THEN 1 ELSE 0
END AS "Created"
from ymtn.MESSAGE a
left join YMTN.WORKGROUP b
ON a.FROM_WG_ID=b.WORKGROUP_ID
where b.WORKGROUP_ID='1STOP_PROCESS'
) a