SELECT计算中的SQL子查询

时间:2016-04-13 15:04:20

标签: sql subquery netezza

对子查询很新,发现自己需要帮助。

我想从单个数据库查询。在该查询中,我想从该数据库(SUBQ和TOTAL)的两个变量中计算变量。我的问题是这样的:我的SUBQ变量需要受到一组额外的WHERE约束,这些约束将用于整个查询。简化示例代码如下:

create table [blah]
   as select date_part('YEAR',DATE) as Orig_Year,
             sum([SUBQ variable])/sum(TOTAL) as UD_Rate
      from [database]
      where [full query requirements]
      group by date_part('YEAR',DATE)

我试图通过在FROM语句中指定子查询来在该计算中创建子查询。所以,例如,

             select date_part('YEAR',DATE1) as Orig_year,
                    sum(a.SUBQ)/sum(b.TOTAL) as UD_Rate
             from database b,
                  (select SUBQ
                   from database
                   where DATE2 is not null and
                         months_between(DATE3,DATE2) <= 100 and
                         VALUE1 in ('A','B')) a
             where VALUE2 between 50.01 and 100
             group by date_part('YEAR',DATE1)

我的想法是否在正确的轨道上?我还没有接近功能性查询的任何地方,并且没有运气在网上找到类似的问题,所以我已经把我的手扔到了你身边。虽然我对它们知之甚少,但是创建一个带有SUBQ值的VIEW,然后将它与更广泛的查询合并会更合适吗?

对于愿意协助我提出这一要求的人的馅饼和蛋糕的想法。谢谢。

2 个答案:

答案 0 :(得分:1)

我认为你只想在窗口函数中进行条件聚合。像这样:

select sum(case when [subquery requirements] then t.subq else 0 end) / sum(t.Total)
from t;

我很确定这就是你要找的东西。就您的create table

而言
select date_part('YEAR',DATE) as Orig_Year,
       sum(case when ?? then Total else 0 end)/sum(TOTAL) as UD_Rate
  from [database]
  where [full query requirements]
  group by date_part('YEAR', DATE);

我猜测要比较的列是Total,符合when中的条件。

答案 1 :(得分:0)

然后使用Common-Table-Expression:

-- Define the CTE expression name and column list.
WITH subquery (Orig_year, UD_Rate)
AS
-- Define the CTE query.
(
  select date_part('YEAR',DATE1) as Orig_year,
                    sum(a.SUBQ)/sum(b.TOTAL) as UD_Rate
             from database b,
                  (select SUBQ
                   from database
                   where DATE2 is not null and
                         months_between(DATE3,DATE2) <= 100 and
                         VALUE1 in ('A','B')) a
             where VALUE2 between 50.01 and 100
             group by date_part('YEAR',DATE1)
)

然后使用subquery,就像在主查询中使用表一样