1

在这里,我试图在 mysql 中使用 case 来获取产品的数量。我的样本数据是

 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     
4

1 回答 1

4

这是 SQLFiddel 演示

以下是方法:

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
于 2013-10-04T05:39:26.900 回答