SQL自带连接与相同字段上的计数功能不同的条款

时间:2018-03-29 16:03:02

标签: sql sql-server-2008 self-join

我对单个表上的单个字段有2个查询,我想加入单个查询...

查询1:

SELECT completed_by_id AS WHO
    , COUNT (activity_id) AS CALLS
FROM table1
WHERE activity_id = 'CALL'
    AND YEAR(completed_date) = YEAR(GETDATE())
    AND MONTH(completed_date) = MONTH(GETDATE())
GROUP BY completed_by_id

返回:

WHO        *    CALLS
Joe Sales  *    5
Jane Sales *    8

查询2:

SELECT completed_by_id AS WHO
    , COUNT (activity_id) AS VISITS
FROM table1
WHERE activity_id = 'VISIT'
    AND YEAR(completed_date) = YEAR(GETDATE())
    AND MONTH(completed_date) = MONTH(GETDATE())
GROUP BY completed_by_id

返回:

WHO        *    VISITS
Joe Sales  *    2
Jane Sales *    3

这两种方法都可以正常工作,但我希望有一个返回类似的查询:

WHO          *   CALLS    *   VISITS  
Joe Sales    *     5      *    2
Jane Sales   *     8      *    3

我知道我需要自我加入,但我不确定如何编写查询。

2 个答案:

答案 0 :(得分:3)

这可以通过在COUNT中使用CASE语句来完成。 COUNT只有在非空时递增,因此当CASE不是您要查找的内容时,可以让CASE返回NULL,或者您可以使用SUM代替并返回1/0。 / p>

SELECT
    completed_by_id AS WHO, 
    COUNT(CASE WHEN (activity_id='CALL' THEN 1 END)) AS CALLS,
    COUNT(CASE WHEN (activity_id='VISIT' THEN 1 END)) AS VISITS
FROM table1
WHERE 
    activity_id IN ('CALL','VISIT') -- This is optional, but it could help efficiency a bit
    AND YEAR(completed_date) = YEAR(GETDATE()) AND 
    MONTH(completed_date) = MONTH(GETDATE())
GROUP BY completed_by_id

答案 1 :(得分:0)

    SELECT completed_by_id AS WHO
    , sum(case when activity_id= 'CALL' then 1 else 0 end) AS CALLS
    , sum(case when activity_id= 'visits' then 1 else 0 end) AS VISITS
FROM table1
WHERE activity_id in  ('CALL','visits')
    AND YEAR(completed_date) = YEAR(GETDATE())
    AND MONTH(completed_date) = MONTH(GETDATE())
GROUP BY completed_by_id