sql语句count怎么使用?
过多繁琐的sql影响代码质量,及维护成本,以下为两种小技巧处理方式,仅供参考。
第一种,用case ---when---方法
select id
,sum(case when type in (1,2) then [count] else 0 end) as sum1
,sum(case when type in (3) then [count] else 0 end) as sum2
,sum(case when type in (4,5) then [count] else 0 end) as sum3
from 表名
group by id
第二种,if 判断
SELECT SUM( goods_amount ) AS money,
count( * ) AS num,
count(if(pay_status=1,true,null)) AS success,
count(if(pay_status=2,true,null)) AS fall
FROM `tab_order_info`
WHERE user_id = 11
SQL中 ALL的用法
ALL
用标量值与单列集中的值进行比较。
语法
scalar_expression
{
=
|
|
!=
|
>
|
>=
|
!>|
<
|
<=
|
!<
}
ALL
(
subquery
)
参数
scalar_expression
是任何有效的
Microsoft®
SQL
Server™
表达式。
{
=
|
|
!=
|
>
|
>=
|
!>
|
<
|
<=
|
!<
}
是比较运算符。
subquery
是返回单列结果集的子查询。返回列的数据类型必须与
scalar_expression
的数据类型相同。
是受限的
SELECT
语句(不允许使用
ORDER
BY
子句、COMPUTE
子句和
INTO
关键字)。
返回类型
Boolean
结果值
如果所有给定的比较对(scalar_expression,
x)均为
TRUE,其中
x
是单列集中的值,则返回
TRUE;否则返回
FALSE。