Oracle SQL将来自同一表的2个查询与2个不同列中的输出结合起来

时间:2018-10-18 08:10:02

标签: sql oracle

我正在使用Oracle SQL数据库。 我正在尝试将这2个查询合并到同一张表中的一个查询中:

select count(CustomerID) from Customers
where (City = 'Berlin' or City = 'London')
from Customers;

select count(CustomerID) from Customers
where (City = 'Mannheim' or City = 'Strasbourg')
from Customers;

我的输出想像是在2列上导出的内容:

| Berlin & London | Mannheim & Strasbourg |
|-----------------------------------------|
|        5        |         10            |

此处为db的示例,https://www.w3schools.com/sql/trysql.asp?filename=trysql_op_in

我认为答案将是:

(select count(CustomerID) from Customers
where (City = 'Berlin' or City = 'London'))
union
(select count(CustomerID) from Customers
where (City = 'Marseille' or City = 'Tsawassen'));
union
(select count(CustomerID) from Customers
where (City = 'Strasbourg' or City = 'Madrid'));

仍在测试...

最后通过这种情况完成了工作。 感谢所有参与的人!

SELECT
  COUNT(CASE
    WHEN  work_zone = 'AMBGI01' OR
          work_zone = 'AMBGI02' OR
          work_zone = 'AMBGI03' AND
          task_type = 'P' THEN work_zone
  END) "HighBay Putaways",
  COUNT(CASE
    WHEN  work_zone = 'AMBGI04' OR
          work_zone = 'AMBGI05' OR
          work_zone = 'AMBGI06' OR
          work_zone = 'AMBGI07' AND
          task_type = 'P' THEN work_zone
  END) "LowBay Putaways",
  COUNT(CASE
    WHEN  from_loc_id = 'THEWALL' AND
          task_type = 'P' THEN from_loc_id
    END) "THE WALL",
    COUNT(CASE
    WHEN  tag_id like '%' AND
          from_loc_id like 'EXPANS%' AND
           task_type = 'P' THEN tag_id
     END) "EXPANSION",
   COUNT(CASE
    WHEN  final_loc_id like '_______' AND
          (status = 'In Progress'        OR
          status = 'Released')          AND
          task_type = 'R' THEN final_loc_id
  END) "Replens"
FROM move_task;

2 个答案:

答案 0 :(得分:2)

不清楚您有两个表(joinselect j.*, a.pass from july j join august a on j.account = a.account where (j.pass = 'yes' and a.pass = 'no') or (j.pass = 'no' and a.pass = 'yes'); )还是一个。如果有两个,则需要向我们展示结构。 w3schools.com说没有像customers这样的表,并且country不包含country列。无论如何,您都需要有条件的customers,如下所示:

store

您也可以使用count,但这更简单,更易读,并且可以在较早的Oracle版本中使用。

答案 1 :(得分:1)

最简单的方法如下:

select count(CASE WHEN City = 'Berlin' or City = 'London' THEN City END) "Berlin & London"
     , count(CASE WHEN City = 'Mannheim' or City = 'Strasbourg' THEN City END) "Mannheim & Strasbourg"
  from Customers