PostgreSQL根据定义的条件搜索查询结果

时间:2018-02-18 15:42:32

标签: sql postgresql

我是初学者,我正在处理一个相当大的查询,它返回大约5万行。 我花了很多时间试图找出问题,看起来我的知识存在差距,如果你能帮助我,我会非常感激。

为了向您展示我决定简化和拆分数据的主要想法。我在这里提出相关表格:

*company*
+----+----------+---------------+----------------+
| ID |   name   | classificaton | special_number |
+----+----------+---------------+----------------+
|  1 | companyX |           309 |            242 |
+----+----------+---------------+----------------+

*branch*
+----+---------------+-------+
| ID |     name      | color |
+----+---------------+-------+
|  1 | environmental | green |
|  2 | navy          | blue  |
+----+---------------+-------+

*company_branch*
+------------+-----------+
| ID_company | ID_branch |
+------------+-----------+
|          1 |         1 |
|          1 |         2 |
+------------+-----------+

好的,因为我们已经提供了所有需要的数据,我需要创建一个查询,它将选择所有公司以及他们正在使用的分支的主要颜色。 companyX可以属于多个分支,但我只需要显示可以根据以下三个条件计算的主分支:

*if classification = 309 and special_number is even then show the relevant color and go the next company (ignore the next conditions)
*if classification = 209 and special_number is even then show the relevant color and go the next company (ignore the next condition)
*else show as grey

我创建了一个类似的查询:(我知道 case 短语不正确,但我保留它,因为它以更好的方式显示我想要完成的事情)

SELECT c.ID, c.name, b.color, c.classification, c.special_number,
CASE 
    WHEN c.classification = 309 AND c.special_number % 2 = 0  THEN b.color
    WHEN c.classification = 209 AND c.special_number % 2 = 0 THEN b.color
    ELSE 'grey'
END AS 'case'
FROM company c INNER JOIN company_branch cb ON c.ID = cb.ID_company
INNER JOIN branch b ON b.ID = cb.ID_branch

然后我得到以下结果

*result*
+----+----------+-------+----------------+----------------+------+
| ID |   name   | color | classification | special_number | case |
+----+----------+-------+----------------+----------------+------+
|  1 | companyX | green |            309 |            242 | green|
|  1 | companyX | blue  |            309 |            242 | blue |
+----+----------+-------+----------------+----------------+------+

问题在于,如果任何公司属于多个分支,那么我总会得到很多颜色......我想得到的是一个只有一种主要分支颜色的公司列表。< / p>

你们可以帮助新手吗?

1 个答案:

答案 0 :(得分:1)

我想你想要这样的东西:

protocol Model {
    func formId() -> String;
    func getById(_ id: String) -> Dictionary<String, Any>?;
    func upsert(_ id: String, withData data: Dictionary<String, Any>);
    func delete(_ id: String);
}

SELECT DISTINCT ON (c.id) c.ID, c.name, COALESCE(b.color, 'grey') as color c.classification, c.special_number, FROM company c LEFT JOIN company_branch cb ON c.ID = cb.ID_company LEFT JOIN branch b ON b.ID = cb.ID_branch ORDER BY c.Id, (CASE WHEN c.classification = 309 AND c.special_number % 2 = 0 THEN 1 WHEN c.classification = 209 AND c.special_number % 2 = 0 THEN 2 ELSE 3 END); 是一个(有用的)Postgres扩展,它在括号中每个项目返回一行。返回的行基于DISTINCT ONGROUP BY中的第一个键需要是项目。以下指定&#34; first&#34;装置

我将连接切换为外连接,因此所有公司都在结果集中。