SELECT
(SELECT mainop
FROM data_final2
WHERE (id = A.id)
AND (os = 1 and test = 2 and mainop BETWEEN 0 AND 500)) AS op1,
(SELECT mainop
FROM data_final2
WHERE (id = A.id)
AND (os = 1 and test = 2 and mainop BETWEEN 500 AND 1000)) AS op2,
(SELECT mainop
FROM data_final2
WHERE (id = A.id)
AND (os = 1 and test = 2 and mainop BETWEEN 1001 AND 1500)) AS op3
FROM data_final2 AS A WHERE A.mainop BETWEEN 0 AND 500 OR A.mainop BETWEEN 500 AND 1000 OR A.mainop BETWEEN 1001 AND 1500
我想在单个SQL查询中编写此查询,而不使用每个输出%来自总计数的子查询。
还想从输出中删除Null
[{"name":"op1","data":[229,null,null,268,null,3
答案 0 :(得分:1)
您可以使用CASE
语句根据同一列中的多个条件显示数据。
SELECT
CASE
WHEN mainop BETWEEN 0 AND 500
AND os = 1 AND test = 2
THEN mainop
ELSE NULL
END as op1
, CASE
WHEN mainop BETWEEN 501 AND 1000
AND os = 1 AND test = 2
THEN mainop
ELSE NULL
END as op2
, CASE
WHEN mainop BETWEEN 1001 AND 1500
AND os = 1 AND test = 2
THEN mainop
ELSE NULL
END as op3
FROM data_final2
WHERE mainop BETWEEN 0 AND 1500
您还可以在同一列上指定多个CASE
语句,以生成不同的数据。
<强>更新强>
重新阅读你的问题后,我认为你实际上可能正在寻找这样的东西:
SELECT 100 * count(CASE
WHEN mainop BETWEEN 0 AND 500
AND os = 1 AND test = 2
THEN 1
ELSE NULL
END) * 1.0 / (SELECT count(*) FROM data_final2) AS 'op1'
,100 * count(CASE
WHEN mainop BETWEEN 501 AND 1000
AND os = 1 AND test = 2
THEN 1
ELSE NULL
END) * 1.0 / (SELECT count(*) FROM data_final2) AS 'op2'
,100 * count(CASE WHEN mainop BETWEEN 1001 AND 1500
AND os = 1 AND test = 2
THEN 1
ELSE NULL
END) * 1.0 / (SELECT count(*) FROM data_final2) AS 'op3'
FROM data_final2
WHERE mainop BETWEEN 0 AND 1500
如果您要将此行显示为百分比数字,请查看您的特定RDBMS函数,以将数据转换为适当的类型。