【问题标题】:Basic Teradata SQL add column and summing columns基本 Teradata SQL 添加列和求和列
【发布时间】:2017-08-11 18:52:21
【问题描述】:

SQL 不太好,如果我的问题看起来很愚蠢,很抱歉。我有这个工作代码,可以提取进入日期和在该日期进入商店 1 的人数。

select entry_date as Enter_Date
    ,count(entry_date) as Entries
    from db_entry
    where entry_date between '2017-03-05' and '2017-03-11'
    and entry_code like 'STR1%'
    group by entry_date

这就是它的显示

Enter_Date  Entries
3/5/2017    35
3/9/2017    30
3/10/2017   27
3/8/2017    23
3/7/2017    29
3/6/2017    32
3/11/2017   39

我想知道是否有办法为商店 2 添加另一列,其中 entry_code 是“STR2%”。我不确定该怎么做的原因是因为我没有从 db_entry 中提取不同的列,所以我不确定如何区分 WHERE 子句中的两列。

此外,我想知道是否有一种快速方法可以对每列求和并将最新日期作为输入日期。理想情况下,这是我希望我的表看起来的样子:

 Enter_Date  Store 1     Store 2 
 3/11/2017   215         301

【问题讨论】:

    标签: sql teradata


    【解决方案1】:

    使用case 表达式进行条件计数。

    select entry_date as Enter_Date,
           count(case when entry_code like 'STR1%' then entry_date end) as Entries1,
           count(case when entry_code like 'STR2%' then entry_date end) as Entries2
    from db_entry
    where entry_date between '2017-03-05' and '2017-03-11'
      and entry_code like any ('STR1%', 'STR2%')
    group by entry_date
    

    注意:WHERE 子句的 like str1/str2 现在并不真正需要,但可能会加快查询速度。

    编辑:现在使用like any,正如@Dudu Markovitz 所建议的那样!

    【讨论】:

    • between date '2017-03-05' and date '2017-03-11'
    • entry_code like any ('STR1%','STR2%')(Teradata 支持的语法)
    • @DuduMarkovitz,感谢您的改进建议!只是古玩,有like all吗?
    【解决方案2】:

    要回答您的第二个问题,只需删除 GROUP BY 并切换到:

    select MAX(entry_date) as Enter_Date,
           count(case when entry_code like 'STR1%' then entry_date end) as "Store 1",
           count(case when entry_code like 'STR2%' then entry_date end) as "Store 2"
    from db_entry
    where entry_date between date '2017-03-05' and date '2017-03-11'
      and entry_code like any ('STR1%', 'STR2%')
    

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多