我有以下查询:
SELECT
"metaCAE"."family",
"metaCAE"."name",
COUNT(1) AS "count"
FROM
"userHistoryProfessional"
INNER JOIN
"company_metaCAE"
ON (
"company_metaCAE"."id_company" = "userHistoryProfessional"."id_company"
)
INNER JOIN
"metaCAE"
ON (
"metaCAE"."id" = "company_metaCAE"."id_metaCAE"
)
WHERE
"userHistoryProfessional"."dateUntil" IS NULL
GROUP BY
"metaCAE"."family"
ORDER BY
"count" DESC;
metaCAE表的架构是
id
level
family
name
如果多个名称属于同一系列,并且只有一个名称是该系列的父级,则具有最低级别(1)。
示例,不包括id列:
level family name
1 A Pork
2 A Pork-Products
3 A Pork-Products Incorporated
1 B Cork
2 B Cork-Products
3 B Cork-Products Incorporated and Sons
3 B Cork Incorporated
问题是我只希望每个系列的父级别(1)的名称出现在我的连接上,但company_metaCAE.id_metaCAE仅引用metaCAE表中的子级别名称(实际公司名称)。
所以,我想要做的是获得一个结果,我用相应的父级名称替换子级别名称。在我的架构中,这是具有最低级别和相同系列的名称。
所以不是这个结果:
family count family-name
A 1 Pork-Products Incorporated
B 2 Cork Incorporated
我想要像
这样的东西family count family-name
A 1 Pork
B 2 Cork
答案 0 :(得分:2)
您需要在查询中添加另一个内部联接:
SELECT
"metaCAE"."family",
parentMetaCAE."name",
COUNT(1) AS "count"
FROM
"userHistoryProfessional"
INNER JOIN
"company_metaCAE"
ON (
"company_metaCAE"."id_company" = "userHistoryProfessional"."id_company"
)
INNER JOIN
"metaCAE"
ON (
"metaCAE"."id" = "company_metaCAE"."id_metaCAE"
)
INNER JOIN ---- PARENT INNER JOIN
(SELECT family, name
FROM metaCAE
WHERE level = 1) parentMetaCAE
ON (parentMetaCAE.family = metaCAE.family)
WHERE
"userHistoryProfessional"."dateUntil" IS NULL
GROUP BY
"metaCAE"."family"
ORDER BY
"count" DESC;