12

您可以为 from 子句分配别名吗?喜欢:

select a - b "Markup" from retail a, cost b;

编辑:对不起,我输入得太快了,并试图将问题简化到没有任何意义的地步

我实际上想要做的是使用别名来比较同一张表中两个发布日期之间的月份。这是我发现的作品:

select distinct to_char(months_between((select distinct pubdate
                                        from books3 
                                        where pubid = 2), 
                                       (select distinct pubdate 
                                        from books3 
                                        where pubid = 4)), '99.99') "Answer"
                              from books3

我希望它看起来像这样:

select distinct months_between(a,b)
from (select distinct pubdate 
       from books3 
       where pubid = 2 as a), 
     (select distinct pubdate 
      from books3 
      where pubid = 4 as b)

但这不起作用

4

2 回答 2

21

是的,Oracle 支持表别名。它支持ASSELECT列表中但不在FROM列表中:

SELECT a.col - b.col AS markup
  FROM RETAIL a,
       COST b
 WHERE b.id = a.id

大多数数据库都支持省略AS关键字。

也就是说,表别名不是列别名——您仍然需要在 SELECT 子句中引用相应表中的特定列,就像您在我的示例更新中看到的那样。我还添加了WHERE条件,因此查询不会返回笛卡尔积。

派生表/内联视图有时需要表别名(AKA 子查询,尽管我发现术语非常模糊):

SELECT x.col
  FROM (SELECT t.col,
               MAX(t.date)
          FROM TABLE t
      GROUP BY t.col) x

这是您的查询:

您的问题是您将表别名放在派生表中,而它需要位于方括号/括号之外:

SELECT DISTINCT TO_CHAR(MONTHS_BETWEEN(x.pubdate, y.pubdate), '99.99') AS "Answer"
 FROM (SELECT DISTINCT a.pubdate FROM BOOKS3 a WHERE a.pubid = 2) x,
      (SELECT DISTINCT b.pubdate FROM BOOKS3 b WHERE b.pubid = 4) y

您需要 distinct 的原因是笛卡尔积。

于 2011-02-09T01:47:22.160 回答
0

最接近您所拥有的是将AS alias移出子查询

select distinct months_between(a.pubdate,b.pubdate)
from (select distinct pubdate 
       from books3 
       where pubid = 2) as a ,
     (select distinct pubdate 
      from books3 
      where pubid = 4) as b;

但是,查询仍然没有多大意义。如果有 2 条记录pubid=2和 3条记录pubid=4,则输出中有 6 行....

months_between(a1, b1)
months_between(a2, b1)
months_between(a1, b2)
months_between(a2, b2)
months_between(a1, b3)
months_between(a2, b3)

我怀疑您实际上正在进行一些分组,因此这将在每个 bookid 级别比较 pubid=2 和 pubid=4 条目。

select
    bookid,
    to_char(months_between(
        max(case when pubid=2 then pubdate end),
        max(case when pubid=4 then pubdate end)), '99.99') "Answer"
from books
group by bookid;
于 2011-02-09T02:02:53.427 回答