具有关系和列比较的SQL查询

时间:2019-03-13 23:22:15

标签: sql postgresql

我正在尝试使用SQL(Postgres)语句执行以下操作:

选择其中equipments.yard_id = yard.id和设备的所有码。 equipment_type_id = 3,4,6和equipments.quantity(equipment_type_id = 6)大于equipment_type_id 3和4的总数

Yards:
+----+--------+
| id |  name  |
+----+--------+
|  1 | Yard 1 |
|  2 | Yard 2 |
|  3 | Yard 3 |
+----+--------+

Equipments:

+----+---------+-------------------+----------+
| id | yard_id | equipment_type_id | quantity |
+----+---------+-------------------+----------+
|  1 |       1 |                 3 |        4 |
|  2 |       2 |                 3 |        5 |
|  3 |       1 |                 6 |        4 |
|  4 |       2 |                 4 |        2 |
|  5 |       2 |                 6 |        2 |
+----+---------+-------------------+----------+

我尝试过:

SELECT
  *
FROM
  yards y
  JOIN equipments e
    ON e.yard_id=y.id AND e.equipment_type_id=3 OR e.equipment_type_id=4 AND e.equipment_type_id=6

当前返回哪个具有equipment_type_id 3或4和6的所有码。我需要对其进行调整,因此我返回其中equipment_type_id = 6的总和大于3和4的总和的所有码。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

显然,这需要聚合。最终条件是一个HAVING子句:

SELECT y.id
FROM yards y JOIN
     equipments e
     ON e.yard_id = y.id AND e.equipment_type_id IN (3, 4, 6) 
GROUP BY y.id
HAVING (SUM(quantity) FILTER (WHERE e.equipment_type IN (6)) >
        SUM(quantity) FILTER (WHERE e.equipment_type IN (3, 4))
       );

答案 1 :(得分:0)

感谢Gordon的帮助,我调整了他的查询,使其可用于较旧版本的Postgres:

SELECT y.name
FROM yards y JOIN
     equipments e
     ON e.yard_id = y.id AND e.equipment_type_id IN (3, 4, 6) 
GROUP BY y.name
HAVING
    SUM(CASE WHEN e.equipment_type_id IN (6) THEN quantity END) > SUM(CASE WHEN e.equipment_type_id IN (3,4) THEN quantity END)