SQL 中没有第二个子查询的计数

Count without 2nd subquery in SQL

我正在尝试获取在多天内至少订购了 1 件产品的用户数。

交易数Table

usr_id|transt_id|product_id|spend| transaction_date

4       8           32      40      2020-05-08 17:54:59
4       7           31      20      2020-05-01 17:54:59
4       7           31      40      2020-05-01 17:54:59
4       6           20      30      2020-05-02 17:54:59
4       6           19      20      2020-05-02 17:54:59
4       6           18      10      2020-05-02 17:54:59
3       5           17      20      2020-05-04 17:54:59
3       5           16      10      2020-05-04 17:54:59
2       3           14      30      2020-05-04 18:54:59
2       3           13      50      2020-05-04 18:54:59
1       2           12      30      2020-05-05 20:54:59
1       2           12      40      2020-05-05 20:54:59
1       2           12      40      2020-05-04 20:54:59
1       1           11      20      2020-05-05 21:54:59
1       1           10      40      2020-05-05 21:54:59
3       4           10      60      2020-05-06 17:54:59

通过我的代码,我已经能够达到输出为:

select user_id, count(*)
from (
select user_id, date(transaction_date)
from transactions
group by user_id, date(transaction_date)) as abc
group by user_id
having count(user_id)>1;

user_id | count
1           2
3           2
4           3

我想写一个代码而不用再写一个子查询来获取 count(*)>1 的用户数; 输出应为:3.
换句话说,我不想要下面的代码;我想少写一个子查询或者一个全新的查询

select count(*)
from (
select user_id, count(*)
from (
select user_id, date(transaction_date)
from transactions
group by user_id, date(transaction_date)) as abc
group by user_id
having count(user_id)>1) as bcd;

您已有的查询可以在没有子查询的情况下编写:

select user_id, count(distinct date(transaction_date)) count
from transactions
group by user_id
having count(distinct date(transaction_date))>1;

所以你现在需要的只需要一个子查询就可以写成:

select count(*) count
from (
  select user_id
  from transactions
  group by user_id
  having count(distinct date(transaction_date))>1
) t

你可以得到与EXISTS相同的结果:

select count(distinct t.user_id) count
from transactions t
where exists (
  select 1 
  from transactions
  where user_id = t.user_id and date(transaction_date) <> date(t.transaction_date)
)

参见demo