在一个查询中将两个计数与联接组合 [英] Combining two counts with joins in one query
问题描述
确定 - 希望有人能帮助我在这里奋斗。已尝试使用sum(case when),count(*),子查询没有成功。
基本上我有两个查询,我试图组合成一个,按相同的参数分组。查询:
Ok - hoping someone can help as I'm struggling here. Have tried using sum(case when), count(*), subqueries with no success. Essentially I have two queries I am trying to combine into one, grouped by the same parameter. The queries:
查询1:
SELECT
u.username,
count(*) as 'Total'
FROM log1 L1
JOIN users u on u.userref = L1.userref
WHERE L1.date between @FromDate and @ToDate
GROUP BY u.username
ORDER BY u.username
查询2:
SELECT
u.username,
count(*) as 'Total'
FROM log2 L2
LEFT JOIN users u on u.userref = L2.userref
WHERE L2.date between @FromDate and @ToDate and L2.message like '%None%'
GROUP BY u.username
ORDER BY u.username
我想是一个单一查询,用户名列(u.username),一列显示查询1的结果,一列显示查询二的结果。任何帮助赞赏!
What I would like is a single query with a username column (u.username), a column showing the results of query 1, and a column showing the results of query two. Any help appreciated!
推荐答案
您可以将count语句放在count函数中, p>
You can put a case statement inside the count function to only count when certain criteria is met:
SELECT u.username,
Total = COUNT(*),
Total2 = COUNT(CASE WHEN L.message LIKE '%None%' THEN 1 END)
FROM log1 AS L
JOIN users AS u
ON u.userref = L.userref
WHERE L.date BETWEEN @FromDate and @ToDate
GROUP BY u.username
ORDER BY u.username;
注意:
- BETWEEN can cause problems, especially when working with dates
- Using string literals for column aliases is on the deprecation list
EDIT
完全错过了有两个单独的日志表:
Completely missed that you had two separate log tables:
SELECT u.username,
Total = COUNT(Count1),
Total2 = COUNT(Count2)
FROM ( SELECT l.UserRef, Count1 = 1, Count2 = NULL
FROM log1 AS L
WHERE L.date BETWEEN @FromDate and @ToDate
UNION ALL
SELECT l.UserRef, Count1 = NULL, Count2 = 1
FROM log2 AS L
WHERE L.date BETWEEN @FromDate and @ToDate
AND L.message LIKE '%None%'
) AS l
JOIN users AS u
ON u.userref = L.userref
GROUP BY u.username
ORDER BY u.username;
这篇关于在一个查询中将两个计数与联接组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!