创建总计的MySQL / SQL select语句的最佳方法(计算'AS'列)?

时间:2022-11-23 22:22:38

I am having some trouble finding how to total 'AS' columns in my select statement.

我在查找如何在select语句中总计'AS'列时遇到了一些麻烦。

example issue:

示例问题:

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

The above does not appear to work, unless I create a count(case) that includes previous 'As' columns initial criteria.

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

Is there a simpler way to do this? Some of my statements become quite (and seemingly unnecessarily) complex.

有更简单的方法吗?我的一些陈述变得非常复杂(看似不必要)。

1 个解决方案

#1


1  

Try editing your query as below:

尝试编辑您的查询,如下所示:

 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

This will work.

这会奏效。

#1


1  

Try editing your query as below:

尝试编辑您的查询,如下所示:

 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

This will work.

这会奏效。