SQL 内连接两个表并根据条件从第二列中提取布尔值

SQL Inner join two tables and extract a boolean value from second column based on condition

我有一个 table 如下所示。让我们称之为 Transactions

id   scan_id   amount   date           description
1       123      10     2020-12-01      "tissue"
1       111      500    2020-12-01      "amount to mexico"
1       124      15     2020-12-01      "dairy product"
2       222      1000   2020-13-01      "amount to India"
2       154      10     2020-13-01      "dairy"
3       333      499    2020-14-01      "amt to philipines"
-
-
-
-

我想要 (111,222,333) 中 scan_id 的所有交易以及一个布尔值,指示客户是否在同一日期进行了 scan_id(111,222,333) 以外的任何其他交易。 这里 scan_ids (111,222,333) 指的是 Money Tx,其他的不是。 所需数据示例如下

id   scan_id   amount   date           description            same_day_non_money_tx
1       111      500    2020-12-01      "amount to mexico"        Yes
2       222      1000   2020-13-01      "amount to India"         Yes
3       333      499    2020-14-01      "amt to philipines"       No

我想像下面这样进行内部连接

select id, scan_id, amount, date, description
from transactions where scan_id in (111,222,333) as T1
inner join 
select id, scan_id, amount, date, description
from transactions where scan_id not in (111,222,333) as T2
on T1.id = T2.id
and T1.date = T2.date

但这给了我所有基于 ID 和日期匹配的交易。我如何将此匹配作为一个单独的列?

您可以使用window函数,如果您需要详细信息:

select t.*,
from (select t.*,
             sum(case when scan_id in (111, 222, 333) then 1 else 0 end) over (partition by id, date) as num_123,
             count(*) over (partition by id, date) as num
      from t
     ) t
where cnt <> num_123 and num_123 > 0;

使用 inner joingroup by 日期条件 if count(*) > 1 then Yes

select t1.*, case when count > 1 then 'Yes' else 'NO' end as same_day_non_money_tx from
(select * from my_table where scan_id in (111, 222, 333) ) t1
inner join 
(select count(*), date from my_table group by date) t2
on (t1.date = t2.date)
order by date;