Basic Teradata SQL 添加列和求和列

Basic Teradata SQL add column and summing columns

不适合 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 子句中的两列。

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

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

使用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 所建议的!

要回答您的第二个问题,只需删除 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%')