在一个查询中将两个计数与联接组合在一起

时间:2014-06-10 16:17:57

标签: sql sql-server join count case-when

好的 - 希望有人可以帮忙,因为我在这里挣扎。尝试过使用sum(case when),count(*),子查询没有成功。 基本上我有两个查询我试图合并为一个,由相同的参数分组。查询:

查询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结果的列,以及一个显示查询二的结果的列。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

您可以在count函数中放置一个case语句,仅在满足某些条件时进行计数:

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;

值得注意的是:

修改

完全错过了你有两个单独的日志表:

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;

答案 1 :(得分:1)

           SELECT X.USERNAME,X.TOTAL,Y.TOTAL 
    FROM(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

            ) as x
INNER JOIN
            (
            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
            ) AS Y ON Y.USERNAME = X.USERNAME