CASE语句

CASE 语句属于SQL标准的条件表达式。

SELECT
	CASE WHEN O.id IS NULL THEN false ELSE true END as used,
	D.status,
	count(*) AS sc 
FROM partition P
	join disk D on P.disk_id=D.id
	left join osd O on o.partition_id=P.id
GROUP BY used, D.status;

当结果中的O.id IS NULL时,used列的值为false,否则为true

WITH语句

WITH 语句用于将指定的子查询的结果保存在一张临时表中,可以在主查询中使用这张表。一个常用的场景是通过WITH语句指定主查询中要用到的条件值。

WITH timerange AS (
	SELECT
		timestamp with time zone '2018-07-27 14:00:00+08:00' AS begin_time,
		timestamp with time zone '2018-08-30 10:00:00+08:00' AS end_time
)
SELECT V.id, V.name,
	CAST(avg(VS.total_iops) AS bigint) AS total_iops,
	CAST(avg(VS.total_bandwidth_kbyte) AS bigint) AS total_bandwidth_kbyte,
	max(VS.created_at) AS "created_at"
FROM volume V join volume_stat VS on V.id=VS.volume_id
WHERE VS.created_at >= (SELECT begin_time FROM timerange) AND VS.created_at < (SELECT end_time FROM timerange)
GROUP BY V.id, V.name
ORDER BY total_iops DESC, total_bandwidth_kbyte DESC;

这个例子中,前面的WITH语句指定了匹配的数据的起止时间。


知识共享许可协议本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。