oracle中有decode函数,如下:
select sum(decode(sex,'男',0,1)) 男生数 from school;
统计男生数目,含义为:decode()中sex字段为男时,用1代替,然后计算总和
而mysql中没有该函数,替代的有case与if函数。
case函数
同样统计男女生人数,语句如下:
SELECT school,COUNT(school) 人数,
SUM(CASE
WHEN sex='男'THEN 1
ELSE 0
END)
男生数,
SUM(CASE
WHEN sex='女'THEN 1
ELSE 0
END)
女生数
FROM sch
GROUP BY sex,school
CASE可能是 SQL 中被误用最多的关键字之一。虽然你可能以前用过这个关键字来创建字段,但是它还具有更多用法。例如,你可以在WHERE子句中使用CASE。
首先让我们看一下CASE的语法。在一般的SELECT中,其语法如下:
SELECT=CASEWHENTHENWHENTHENELSEEND
在上面的代码中需要用具体的参数代替尖括号中的内容。下面是一个简单的例子:
USEpubs
GOSELECT Title,
'Price Range'=CASEWHENpriceISNULLTHEN'Unpriced'WHENprice<10THEN'Bargain'WHENpriceBETWEEN10and20THEN'Average'ELSE'Gift to impress relatives'ENDFROMtitles
ORDERBYprice
GO
这是CASE的典型用法,但是使用CASE其实可以做更多的事情。比方说下面的GROUPBY子句中的CASE:
SELECT'Number of Titles',Count(*)
FROMtitles
GROUPBYCASEWHENpriceISNULLTHEN'Unpriced'WHENprice<10THEN'Bargain'WHENpriceBETWEEN10and20THEN'Average'ELSE'Gift to impress relatives'ENDGO
你甚至还可以组合这些选项,添加一个ORDERBY子句,如下所示:
USEpubs
GOSELECTCASEWHENpriceISNULLTHEN'Unpriced'WHENprice<10THEN'Bargain'WHENpriceBETWEEN10and20THEN'Average'ELSE'Gift to impress relatives'ENDASRange,
Title
FROMtitles
GROUPBYCASEWHENpriceISNULLTHEN'Unpriced'WHENprice<10THEN'Bargain'WHENpriceBETWEEN10and20THEN'Average'ELSE'Gift to impress relatives'END,
Title
ORDERBYCASEWHENpriceISNULLTHEN'Unpriced'WHENprice<10THEN'Bargain'WHENpriceBETWEEN10and20THEN'Average'ELSE'Gift to impress relatives'END,
Title
GO
注意,为了在GROUPBY块中使用CASE,查询语句需要在GROUPBY块中重复SELECT块中的CASE块。
if语句
同样统计男女生人数,语句如下:
SELECT school,COUNT(school) 人数,SUM(IF(sex='男',1,0)) 男生数,SUM(IF(sex='女',1,0)) 女生数,
SUM(IF(pass=1,1,0)) pass1,SUM(IF(pass=0,1,0)) pass0,
SUM(IF(state=1,1,0)) state1,SUM(IF(state=0,1,0)) state0
FROM sch
GROUP BY sex,school
语法和decode类似。