下面是我正在尝试做的示例查询,它完成了工作,但我觉得子查询不是最好的方法。有什么指针吗?
SELECT DISTINCT
u.UserID,
(SELECT COUNT(LoginID) FROM Logins WHERE Success = 1 AND UserID = u.UserID) AS Successful,
(SELECT COUNT(LoginID) FROM Logins WHERE Success = 0 AND UserID = u.UserID) AS Unsuccessful,
(SELECT TOP 1 LoginDate FROM Logins WHERE UserID = u.UserID ORDER BY LoginDate DESC) AS LastLogin
FROM
Users u INNER JOIN
Logins l ON u.UserID = l.UserID
顺便说一句,上面的例子看起来不像需要加入,但在真正的解决方案中,我做了其他一些列...
答案 0 :(得分:6)
我是否遗漏了重要的内容,或者您是否可以通过单个聚合查询执行此操作?
SELECT u.UserID,
SUM(CASE WHEN Success = 1 THEN 1 ELSE 0 END) AS Successful,
SUM(CASE WHEN Success = 0 THEN 1 ELSE 0 END) AS Unsuccessful,
MAX(LoginDate) AS LastLogin
FROM Users u
INNER JOIN Logins l on u.UserID = l.UserID
GROUP BY u.UserID
答案 1 :(得分:1)
我会尝试这样的事情:
declare @Users Table (UserID int)
declare @Logins Table (LoginID int, UserID int, LoginDate DateTime, Success Bit)
Insert into @Users
select 1 union select 2
insert into @Logins
select 1, 1, '2010-10-13 6:00:00', 1
union
select 2, 1, '2010-10-13 7:00:00', 0
union
select 3, 1, '2010-10-13 8:00:00', 1
union
select 4, 2, '2010-10-13 6:00:00', 0
union
select 5, 2, '2010-10-13 7:00:00', 1
union
select 6, 2, '2010-10-13 9:00:00', 1
union
select 7, 2, '2010-10-13 10:00:00', 1
Select UserID,
[1] As Successful,
[0] As Unsuccessful,
LoginDate As LoginDate
From (
SELECT
u.UserID,
l.LoginID,
l.Success,
Max(LoginDate) Over (Partition By u.UserID) As LoginDate
FROM @Users u
INNER JOIN @Logins l ON u.UserID = l.UserID
) Data Pivot (
Count(LoginID) For Success In (
[0], [1]
)
) Result
答案 2 :(得分:0)
您可以尝试在您的情况下更有效:
select
u.UserID,
sum(case when l.Success = 1 then 1 else 0 end) as Successful,
sum(case when l.Success = 0 then 1 else 0 end) as Unsuccessful,
max(LoginDate) as LastLogin
from
Users u
inner join Logins l on l.UserID = u.UserID
group by
u.UserId