计算一列的不同值

时间:2018-08-23 15:37:18

标签: sql teradata distinct-values

我正在使用以下输出运行以下查询。...

"The Term' means commencing on and including October."

我正在尝试获取days_used列以计算dt列中的不同值,因此我的days_used列应全部为4而不是1。更改代码有帮助吗?我希望尽可能地更改用于导出days_used的选择结构。

2 个答案:

答案 0 :(得分:0)

您真正想要的是:

    Count(DISTINCT Cast(g.dts AS DATE)) over () AS days_used

但是Teradata不支持带有窗口功能的count(distinct)。因此,您可以使用:

select . . .,
       sum(case when seqnum = 1 then 1 else 0 end) as num_different_dates
from (select . . .,
             row_number() over (partition by Cast(g.dts AS DATE) order by g.dts) as seqnum
      from db1.table1 g join
           db2.table2 f
           on f.fac_id = g.fac_id and
              g.ticket = '07100103031500002' and    
              f.loc IN (80007944, 80007838, 80007998, 80007823)
     ) gf
. . .

答案 1 :(得分:0)

正如戈登已经解释的那样,您需要使用两个Window函数重写COUNT(DISTINCT) OVER

在不嵌套在派生表中的情况下获得预期结果的方法是基于不同顺序的DENSE_RANKs

DENSE_RANK() over (order by Cast(g.dts AS DATE) ) +
DENSE_RANK() over (order by Cast(g.dts AS DATE) DESC) - 1

您的情况是:

FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,944  1/2/2016    1   1+4-1=4 
FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,998  1/2/2016    1   1+4-1=4
FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,823  1/3/2016    1   2+3-1=4
FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,944  1/3/2016    1   2+3-1=4
FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,838  1/4/2016    1   3+2-1=4
FB3CDE6B2FBE42BEA2BAD79CACA70055    07100103031500002   80,007,944  7/22/2018   1   4+1-1=4