从customer表中选择customer id with condition,并使用log table-sql统计所有放置的日志

dm7nw8vv  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(257)

我有两张表,定义如下,
表:客户:

ID       | Customer_Name |Sex (bit)
 --------------------------
    1       | John        | men
    2       | Mack        |women
    3       | Andy        |women

表:日志:

ID      | Customer_ID| Date
 --------------------------
    1      | 1        | 2020-06-03
    2      | 3        |2020-06-03

我想写一个查询来选择每个带有性别条件的名字,以及每个客户使用join放置的所有日志的计数。结果是,

1 |  1
2 |  0
3 |  0

我的问题:

(SELECT Customer.ID,  COUNT(Log.Customer_ID) as number 
 from 
 Customer
  Left JOIN 
   Log
     on 
      Customer.Sex=0 and
       Customer.ID=Log.Customer_ID
        and  
        Log.Date>='2020-06-13' 
        group by Customer.ID)

但是它返回了错误的结果。请告知

ej83mcc0

ej83mcc01#

使用条件聚合

SELECT Customer.ID,  COUNT(case Customer.Sex when 0 then Log.Customer_ID end) as number 
 from 
 Customer
  Left JOIN 
   Log
     on 
       Customer.ID=Log.Customer_ID
        and  
        Log.Date>='2020-06-13' 
        group by Customer.ID

如果只需要男性/女性,则将 predicate 移动到 WHERE ```
select Customer.ID, COUNT(Log.Customer_ID) as number
from Customer
left join Log
on Customer.ID=Log.Customer_ID
and Log.Date>='2020-06-13'
where Customer.Sex = 0
group by Customer.ID

bjp0bcyl

bjp0bcyl2#

你能显示这个查询返回的结果吗?
我认为左连接不是一个好方法,如果您想在on子句中进行过滤(或者只使用where),我会尝试使用内部连接。

(SELECT Customer.ID,  COUNT(Log.Customer_ID) as number 
from Customer
JOIN Log on Customer.Sex=0 and Customer.ID=Log.Customer_ID and Log.Date>='2020-06-13' 
group by Customer.ID)

相关问题