我正在运行mariaDB版本的mysql,查询结果如下
select count(*) as 'Non-HT Computes', vcpus_used as 'Status'
from compute_nodes
WHERE deleted_at is NULL
AND hypervisor_hostname LIKE '%sriov%'
AND vcpus < '21'
GROUP BY vcpus_used
+-----------------+--------+
| Non-HT Computes | Status |
+-----------------+--------+
| 20 | 0 |
| 5 | 16 |
+-----------------+--------+
这是我要尝试的操作,如果在Status
列中值为0
然后打印Available
,并且如果值在16
到20
之间值In-used
,如何即时更改返回值的结果?
最终结果应类似于
+-----------------+----------------+
| Non-HT Computes | Status |
+-----------------+----------------+
| 20 | Available |
| 5 | In-Used |
+-----------------+----------------+
我尝试过CASE
语句,但是不确定如何将其与别名Status
列放在一起,因为Status
是伪列。
编辑:
我已经走了这么远,但无法找出如何打印Non-HT Computes
表格:(
select CASE WHEN Status = 0 THEN 'available' ELSE 'In-used' END AS Status from (select count(*) as 'Non-HT Computes',vcpus_used as 'Status' from compute_nodes WHERE deleted_at is NULL AND hypervisor_hostname LIKE '%sriov%' AND vcpus < '21' GROUP BY vcpus_used) as a
+-----------+
| Status |
+-----------+
| available |
| In-used |
+-----------+
答案 0 :(得分:2)
这可以完成工作。如果要在非零情况后进行限制,则可以使用having
语句。
SELECT count(*) AS 'Non-HT Computes',
CASE
WHEN vcpus_used BETWEEN 16 AND 20 THEN "In-used"
WHEN vcpus_used = 0 THEN "Available"
ELSE "Non-Zero"
END AS Status
FROM compute_nodes
WHERE deleted_at IS NULL
AND hypervisor_hostname LIKE '%sriov%'
AND vcpus < '21'
GROUP BY vcpus_used;
答案 1 :(得分:2)
第一种选择是使用CASE
:
SELECT count(*) AS 'Non-HT Computes',
CASE
WHEN vcpus_used = 0 THEN 'Available'
WHEN vcpus_used >= 16 AND vcpus_used <= 20 THEN 'In-use'
END AS 'Status'
FROM compute_nodes
WHERE deleted_at IS NULL
AND hypervisor_hostname LIKE '%sriov%'
AND vcpus < '21'
GROUP BY vcpus_used
第二个选项是创建一个表,该表具有状态值(0、16、20)并针对该表进行联接。
CREATE TABLE status_text (
id INT PRIMARY KEY,
descr VARCHAR(32)
);
INSERT INTO status_text VALUES (0,'Available');
INSERT INTO status_text VALUES (16,'In-use');
INSERT INTO status_text VALUES (20,'In-use');
SELECT count(*) AS 'Non-HT Computes',descr AS status
FROM compute_nodes
JOIN status_text ON (id=vcpus_used)
WHERE deleted_at IS NULL
AND hypervisor_hostname LIKE '%sriov%'
AND vcpus < '21'
GROUP BY vcpus_used