如何将这两个查询合并为一个查询,但将每个查询的输出放在单独的列中

问题描述 投票:0回答:1

我可以在单个查询中运行这两个查询并将每个查询的结果数据存储在单独的列中吗?

select stars as Med
from business
where city = "Pittsburgh" and is_open = 1 and stars between 2 and 3

select stars as High
from business
where city = "Pittsburgh" and is_open = 1 and stars between 4 and 5 

我尝试过:

select stars as Med
from business
where city = "Pittsburgh" and is_open = 1 and stars between 2 and 3
Union
select stars as High
from business
where city = "Pittsburgh" and is_open = 1 and stars between 4 and 5 

但我只得到了“Med”专栏

+-----+
| med |
+-----+
| 2.0 |
| 2.5 |
| 3.0 |
| 4.0 |
| 4.5 |
| 5.0 |
+-----+
sqlite
1个回答
0
投票

您发现 UNION 扩展/附加了额外的行。如果您想要其他列,那么您可以将它们作为要输出的列包含在内。

但是,执行后者时,如果没有一些将中值和高值配对的标准,则另一列需要具有一些值,例如空。

如果没有任何此类标准,您可以通过使用以下方式满足您的问题:-

SELECT 
    CASE WHEN stars >= 2.0 AND stars <= 3 THEN stars ELSE null END AS med, 
    CASE WHEN stars > 3.0 AND stars <= 5.0 THEN stars ELSE null END AS high 
FROM business;

这会导致:-

© www.soinside.com 2019 - 2024. All rights reserved.