如果聚合函数中存在特定代码,则在 T-SQL 中包含附加列

In T-SQL include additional column if a specific code exists in an aggregate function

我希望在查询中包含一个附加列,这将是一个简单的位类型列 - 是或否。目前,它会提取日期范围内的销售额及其唯一的 SaleID,以及数字使用 COUNT 销售的商品数量。我想要做的是让下一栏说明这次销售是否包含特定商品(使用它的商品代码)。

理想情况下输出是;

[SALE DATE] / [COUNT(Items)] / [Item #111 Included?]
29/07/2020 / 54 / No
28/07/2020 / 21 / No
28/07/2020 / 43 / Yes
27/07/2020 / 8 / No

我试过尝试使用 CASE,但它迫使我按 ItemID 分组。任何人都知道这是否可行,如果可行 - 我需要使用哪些功能来实现这一目标。干杯。

我怀疑您需要条件聚合。我会把计数放在:

select sale_date, count(*),
       sum(case when item = 111 then 1 else 0 end) as cnt_111
from t
group by sale_date;

通过将 sum() 更改为 max() 您可以获得 0/1 标志:

select sale_date, count(*),
       max(case when item = 111 then 1 else 0 end) as flag_111
from t
group by sale_date;

如果您希望此为 'yes''no',则:

select sale_date, count(*),
       max(case when item = 111 then 'yes' else 'no' end) as flag_yn_111
from t
group by sale_date;