Mysql Between Clause inside Case when语句并计算列中的项目数

标签 mysql count case

在这里,我试图通过在 mysql 中使用 case when 来获取产品的数量。 我的示例数据是

 ID | Proname | led | lcd | hd | fullhd | 3d | displaysize (inches) |  brandID
 1    tv1        1     0     0     1       0      22                      3
 2    tv2        0     1     1     0       0      26                      3 
 3    tv3        1     0     1     0       0      32                      3
 4    tv4        1     0     0     1       1      55                      3  
 5    tv5        1     0     0     1       0      42                      3 

现在我的预期输出

lcdcnt | ledcnt | hdcnt | fullhdcnt | 3dcnt | dispcntlessthan32 | displaycntbetwwen32and42 | displaycntabove42
  1        4       2         3          1    

这是我的查询。但我没有得到预期的正确输出

select 
    sum(lcdtv) lcdcnt,
    sum(ledtv) ledcnt,
    sum(3dtv) 3dcnt,
    sum(plasmatv) plasmacnt,
    sum(smarttv) smatcnt,
    sum(hdtv) hdnt,
    sum(fullhdtv) fullhdcnt,
    sum(ultrahdtv) ultrahdcnt,
    sum(4ktv) 4kcnt,
    sum(8ktv) 8kcnt,
    sum(oledtv) oledcnt,
    case
        when (displayinches between 1 and 32) then count(displayinches)
    end as dispcntlessthan32
case
        when (displayinches between 32 and 42) then count(displayinches)
    end as displaycntbetwwen32and42
from
    tv
where
    brandID = 3 and (ledtv = 1) and price != 0     

最佳答案

Here is the SQLFiddel Demo

方法如下:

select 
    sum(lcd) lcdcnt,
    sum(led) ledcnt,
    sum(3d) 3dcnt,
    sum(hd) hdnt,
    sum(fullhd) fullhdcnt,
    sum(3d) 3dcnt,
    sum(case when displaysize between 1  and 32 then 1 else 0 end) as dispcntlessthan32,
    sum(case when displaysize between 33 and 42 then 1 else 0 end) as displaycntbetween32and42
from table1
where brandID = 3

关于Mysql Between Clause inside Case when语句并计算列中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19173687/

相关文章:

mysql - 计算每天两个日期之间的时间

r - 计算数据框或矩阵中非零的数量

SQL 将值更改为大写或小写

php - sql查询 parent 的结果

php - 如何从 URL 中隐藏用户 ID 和密码?

sql - 从按日期排序的列表中选择下一条记录

MySQL:添加到计数大小写...然后

php - codeigniter 查询 Controller View

c++ - 归并排序中反转的反转计数值

Mysql case 语句不起作用