PostgreSQL并加入别名
我有一个查询,以非常简化的形式,看起来像这样:
SELECT aa, bb, xx
FROM (VALUES ('a1', 'b1'), ('a2', 'b2')) as T1(aa, bb)
LEFT JOIN (
SELECT xx FROM (VALUES
('a1', 'y1'), ('x2', 'y2')) as T2(xx, yy)
) as T3 ON T1.aa = T3.xx ;
执行以生成此问题:
aa | bb | xx
----+----+--------
a1 | b1 | a1
a2 | b2 | (NULL)
(2 rows)
在现实生活中,列XX
是使用案例语句和Alias定义的:
SELECT
...,
(CASE WHEN rgr.age_years < 18 THEN '< 18'
WHEN rgr.age_years < 36 THEN '26-35'
WHEN rgr.age_years < 46 THEN '36-45'
WHEN rgr.age_years < 56 THEN '46-55'
WHEN rgr.age_years < 130 THEN '> 55' END)
as row_name,
...
FROM
(VALUES ('< 18'), ('26-35'), ('36-45'),
('46-55'), ('> 55'))
as prn(possible_row_name)
LEFT JOIN other_table rgr
ON prn.possible_row_name = ??row_name??
显然?? ROW_NAME ??
是一个别名,因此在我指定加入时无法使用。但是我没有找到正确的配方。
关键是我正在对表rgr
进行选择,并且我希望所有的年龄段都存在,即使没有实体满足该数字。
I have a query that, in very simplified form, looks like this:
SELECT aa, bb, xx
FROM (VALUES ('a1', 'b1'), ('a2', 'b2')) as T1(aa, bb)
LEFT JOIN (
SELECT xx FROM (VALUES
('a1', 'y1'), ('x2', 'y2')) as T2(xx, yy)
) as T3 ON T1.aa = T3.xx ;
which executes to produce this:
aa | bb | xx
----+----+--------
a1 | b1 | a1
a2 | b2 | (NULL)
(2 rows)
In real life the column xx
is defined using a case statement and alias:
SELECT
...,
(CASE WHEN rgr.age_years < 18 THEN '< 18'
WHEN rgr.age_years < 36 THEN '26-35'
WHEN rgr.age_years < 46 THEN '36-45'
WHEN rgr.age_years < 56 THEN '46-55'
WHEN rgr.age_years < 130 THEN '> 55' END)
as row_name,
...
FROM
(VALUES ('< 18'), ('26-35'), ('36-45'),
('46-55'), ('> 55'))
as prn(possible_row_name)
LEFT JOIN other_table rgr
ON prn.possible_row_name = ??row_name??
Obviously ??row_name??
is an alias and so is not available at the time I specify the join. But I've not found the right formulation.
The point is simply that I'm doing a select on table rgr
and I want all the age tranches present, even if no entity satisfies that number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在表Expression
RGR
中飞行创建列,如以下方式You can create the column on the fly inside the table expression
rgr
, as in: