【问题标题】:Best way to create a MySQL/SQL select statement that totals (count 'AS' columns)?创建总计(计数“AS”列)的 MySQL/SQL 选择语句的最佳方法?
【发布时间】:2017-08-30 03:52:21
【问题描述】:

我在查找如何在我的选择语句中汇总“AS”列时遇到了一些麻烦。

示例问题:

Select *,

count(case when column1 = 'yes' then (value +1) end) AS Column1Count,
count(case when column2 = 'yes' then (value +1) end) AS Column2Count,
(Column1Count + Column2Count) AS Column1and2TOTAL

From mytable

上述方法似乎不起作用,除非我创建一个包含先前“作为”列初始条件的计数(案例)。

有没有更简单的方法来做到这一点?我的一些陈述变得相当(并且看似不必要)复杂。

【问题讨论】:

  • 不幸的是,mySQL 没有 cross apply 的 TSQL 等价物,这会使这很容易。没有将counts 作为子查询,加入它并对其进行总结(这将两次命中表,以及复制任何where 逻辑,因此,可能效率低下)我认为最快的方法是在您的sum 中复制case。留下这个作为评论,因为我希望我错了

标签: mysql select count case


【解决方案1】:

尝试如下编辑您的查询:

 Select Column1Count,
        Column2Count,
        (Column1Count + Column2Count) AS Column1and2TOTAL
 From (
       select count(case when column1 = 'yes' then (value +1) end) AS Column1Count, 
              count(case when column2 = 'yes' then (value +1) end) AS Column2Count 
       from  mytable) as subquery

这会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多