SELECT SQL Query(MySQL)

时间:2017-07-16 11:14:44

标签: mysql sql

我有以下查询:

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

上面的查询给出了这样的结果:

enter image description here

我想在此处添加另一个列,其中" ExpiredCount = TotalCount - ActiveCount "

我怎样才能实现这一目标?

2 个答案:

答案 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