0

我有两个表,其中包含需要计数的数据

登录历史和登录尝试

一种是不包括登录尝试的登录历史表。

Login History 的主键是 REF_ID,但也包含 Customer_ID。Login Attempts 表还包括 Customer_ID

我正在尝试获取特定 Customer_id 的登录尝试次数和登录历史记录。我得到了一个 Customer_ID 的列表并将它们放在一个临时表“#a”中这是我试图用来获取这个计数的查询。

SELECT COUNT (la.customer_ID) as login_attempts FROM
LOGIN_ATTEMPTS la
JOIN LOGIN_HISTORY lh
on la.Customer_ID = lh.customer_ID
where la.customer_ID in (select Customer_ID from #a)group by la.customer_ID

我需要的结果集是 Customer_ID,以及每个客户的登录尝试次数和旁边的历史记录。我尝试了几种不同的方法,但我的 GROUP BY 或 COUNT 语法总是以错误告终。

我还假设我可以在这里的某个地方添加一个 SUM 函数,但我不确定我需要如何构建它。我在这里先向您的帮助表示感谢!

4

3 回答 3

2
Select customer_ID
,(Select Count(*) from LOGIN_ATTEMPTS l where l.customer_ID=a#.ID) as [LOGIN_ATTEMPTS]
,(Select Count(*) from LOGIN_HISTORY h where h.customer_ID=a#.ID) as [LOGIN_HISTORY]
from a#

并且不使用#

Select customer_ID
,(Select Count(*) from LOGIN_ATTEMPTS l where l.customer_ID=a2.ID) as [LOGIN_ATTEMPTS]
,(Select Count(*) from LOGIN_HISTORY h where h.customer_ID=a2.ID) as [LOGIN_HISTORY]
( 
Select Distinct customer_ID from
(
select customer_ID from LOGIN_ATTEMPTS
union
select customer_ID from LOGIN_HISTORY
) a1
)a2
于 2012-11-19T17:21:53.550 回答
1
SELECT 
  COUNT (*)  AS Attempts, 
   la.Customer_ID 
FROM
  LOGIN_ATTEMPTS la
JOIN 
   LOGIN_HISTORY lh
on la.Customer_ID = lh.customer_ID
where 
   la.customer_ID in (select Customer_ID from #a)
group by 
   la.customer_ID
于 2012-11-19T17:15:18.117 回答
1

这是@bummi 第二种方法的变体,没有额外的子查询:

Select customer_ID,
       sum(case when ltype = 'A' then 1 else 0 end) as LoginAttempts,
       sum(case when ltype = 'H' then 1 else 0 end) as LoginHistory
from ((select 'A' as ltype, customer_ID
       from LOGIN_ATTEMPTS
      ) union all
      (select 'H' as ltype, customer_id
       from LOGIN_HISTORY
      ) 
     ) l
where customer_Id in (select Customer_Id from #A)
group by customer_Id
于 2012-11-19T19:13:39.617 回答