我有以下查询:
SELECT
a.source,
TotalCount,
ActiveCount
FROM
(
SELECT COUNT(*) AS TotalCount, a.source
FROM internship a
GROUP BY a.source
) AS A
join
(
SELECT COUNT(*) AS ActiveCount, b.source
FROM internship b
WHERE b.int_lastdate > CURDATE() AND b.status LIKE 'Published'
GROUP BY b.source
) AS B
ON A.source = B.source
上面的查询给出了这样的结果:
我想在此处添加另一个列,其中" ExpiredCount = TotalCount - ActiveCount "
我怎样才能实现这一目标?
答案 0 :(得分:2)
你只需要一个表达式。但是,您可以简化查询:
RTSP/RTP
注意:
select i.source, i.TotalCount, i.ActiveCount,
(i.TotalCount - i.ActiveCount) as ExpiredCount
from (select i.source, count(*) as TotalCount, i.source,
sum(i.int_lastdate > curdate() and i.status like 'Published') as ActiveCount
from internship i
group by i.source
) i;
,只需条件聚合。编辑:
如果要将其用作视图,则不能在join
子句中创建子查询(MySQL限制):
FROM
答案 1 :(得分:1)
戈登的回答可能就是我希望看到DBA继承其他人的代码。但实际上我们可以完全避免使用子查询,只需编写以下内容:
SELECT
source,
COUNT(*) AS TotalCount,
SUM(CASE WHEN int_lastdate > CURDATE() AND status LIKE 'Published'
THEN 1 ELSE 0 END) AS ActiveCount,
COUNT(*) - SUM(CASE WHEN int_lastdate > CURDATE() AND status LIKE 'Published'
THEN 1 ELSE 0 END) AS ExpiredCount
FROM internship
GROUP BY source