我正在尝试选择一些数据但是我遇到了问题,因为这是一个子查询,而子查询中的数据是使用连接的别名。我想设置这个是因为我将以不同的方式在子查询上运行聚合。这是一个例子。我希望你明白我在这里要做的事情。这不是我正在使用的实际数据,因此我想使用以下方法。问题是我正在尝试查询具有别名且具有别名的连接的子查询。
请记住,如果我只选择main_query.FullState,如果我有1个连接,则下面有效,但由于我加入了两次,我需要添加一个别名。这是我遇到麻烦的地方。
USERTABLE ---------------- Name BirthState LivingState David CA CA Roger NY PA
STATESTABLE ---------------- State FullState CA California NY New York PA Philadelphia
select main_query.LivingTable.FullState, count(*) from (
select * from USERTABLE
join STATESTABLE LivingTable on USERTABLE.LivingState = STATESTABLE.State
join STATESTABLE BirthTable on USERTABLE.BirthState = STATESTABLE.State
)main_query
答案 0 :(得分:0)
您可以使用已连接表的别名。你甚至无法访问"内部" table-alias,因为它超出了范围。
如果要检索原始表中具有相同列名的两列,请使用带有AS的列别名。
另一件事:请为这些案件使用WITH。这大大提高了可读性。
WITH main_query AS
(
select lt.FullState AS LivingFullState, bt.FullState AS BirthFullState
from USERTABLE ut
join STATESTABLE lt on lt.LivingState = ut.State
join STATESTABLE bt on bt.BirthState = ut.State
)
select LivingFullState, count(*) from main_query
答案 1 :(得分:0)
你应该能够运行"聚合"和其他类型的查询,而不诉诸"子查询"。只需使用
之类的东西Select living.FullState as "Living State", count(1)
from USERTABLE user JOIN STATESTABLE living on living.LivingState = user.State
类似下面的项目可能也很有用
Select State, Sum(LivingStatePopulation) as "Living State Population", Sum(BirthStatePopulation) as "Birth State Population"
from (Select living.FullState as "State", count(1) as "LivingStatePopulation", 0 as "BirthStatePopulation"
from USERTABLE user JOIN STATESTABLE living on living.LivingState = user.State
UNION
Select birth.FullState as "State", 0 as "LivingStatePopulation", count(1) as "BirstStatePopulation"
)
order by State