我正在处理两个我希望合并为一个的SQL查询,因此第一个查询的结果将在第一列中,而第二个查询的结果将在第二列中。我怎么能实现这个目标呢?
我尝试过联盟,但它会把结果分成两行......那不是我想要的......
select count(*) as ColumnA from Inventory i, Sale s where i.vin=s.vin and i.condition='new'
select count(*) as ColumnB from Inventory i, Sale s where i.vin=s.vin and i.condition='used' order by 1 desc;
答案 0 :(得分:7)
您可以使用稍微不同的查询同时获取两个计数,这比组合两个查询稍微有效:
SELECT
SUM(CASE WHEN i.condition = 'new' THEN 1 ELSE 0 END),
SUM(CASE WHEN i.condition = 'used' THEN 1 ELSE 0 END)
FROM
Inventory i
JOIN
Sale s ON i.vin = s.vin
答案 1 :(得分:6)
您可以在一个查询中使用组合两个子查询,如下所示:
select
(select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='new') as New,
(select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='used') as Used
你想通过声明来实现什么目标?
答案 2 :(得分:3)
一种简单的方法是:
select
(select count(*) as ColumnA from Inventory i, Sale s where i.vin=s.vin and i.condition='new') as newCount,
(select count(*) as ColumnB from Inventory i, Sale s where i.vin=s.vin and i.condition='used') as usedCount
答案 3 :(得分:2)
您可以使用其他SELECT
来合并结果:
SELECT
(select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='new') as ColumnA,
(select count(*) from Inventory i, Sale s where i.vin=s.vin and i.condition='used') as ColumnB