2015-06-05 44 views
2
SELECT u.USER_NAME AS [User] 
    ,COUNT(ad.ACTIVITY_ID) AS [Total Activities Late] 
FROM USERS u 
INNER JOIN ACTIVITY_DATA ad ON u.USER_ID = ad.USER_ID 
WHERE ad.DAYS_LATE > 0 
    AND ad.COMPLETED_DATE IS NULL 
GROUP BY u.USER_NAME 

SELECT u.USER_NAME AS [User] 
    ,COUNT(ad.ACTIVITY_ID) AS [Upto One Week Late] 
FROM USERS u 
INNER JOIN ACTIVITY_DATA ad ON u.USER_ID = ad.USER_ID 
WHERE ad.DAYS_LATE BETWEEN 1 AND 7 
    AND ad.COMPLETED_DATE IS NULL 
GROUP BY u.USER_NAME 

這兩個選項都可以正常工作,但是我想返回活動的總數和總數在同一個SELECT語句中晚了一週的活動。這可能嗎?SQL - 在COUNT中指定一個條件/在同一個字段中多次返回一個值SELECT

我使用SQL Server 2012的

回答

3

你可以,你只需要使用SUM和CASE語句。像這樣的東西應該這樣做:

SELECT u.USER_NAME As [User] 
    , COUNT(ad.ACTIVITY_ID) As [Total Activities Late] 
    , SUM(CASE WHEN ad.DAYS_LATE BETWEEN 1 and 7 THEN 1 ELSE 0 END) As [Upto One Week Late] 
    FROM USERS u 
    JOIN ACTIVITY_DATA ad 
    ON u.USER_ID = ad.USER_ID 
    WHERE ad.DAYS_LATE > 0 AND ad.COMPLETED_DATE is NULL 
    GROUP BY u.USER_NAME 
+0

景氣指定條件,謝謝:)男人 – Matthew

2

嘗試這樣的而不是使用SUM()功能和使用CASE聲明

SELECT u.USER_NAME As [User], 
    SUM(CASE WHEN ad.DAYS_LATE > 0 THEN 1 ELSE 0 END) As [Total Activities Late], 
    SUM(CASE WHEN ad.DAYS_LATE BETWEEN 1 and 7 THEN 1 ELSE 0 END) As [Upto One Week Late] 
    FROM USERS u 
    JOIN ACTIVITY_DATA ad ON u.USER_ID = ad.USER_ID 
    WHERE ad.COMPLETED_DATE is NULL 
    GROUP BY u.USER_NAME 
0
SELECT u.USER_NAME As [User], (SELECT COUNT(ad.ACTIVITY_ID) 
           FROM USERS ua 
           JOIN ACTIVITY_DATA ad ON ua.USER_ID = ad.USER_ID 
           WHERE ad.DAYS_LATE > 0 
           AND ad.COMPLETED_DATE is NULL 
           AND ua.USER_ID = u.USER_ID 
           GROUP BY ua.USER_NAME) As [Total Activities Late], 
           (SELECT COUNT(ad.ACTIVITY_ID) 
           FROM USERS ub 
           JOIN ACTIVITY_DATA ad ON ub.USER_ID = ad.USER_ID 
           WHERE ad.DAYS_LATE BETWEEN 1 
           AND 7 AND ad.COMPLETED_DATE is NULL 
           AND ub.USER_ID = u.USER_ID 
           GROUP BY ub.USER_NAME) As [Upto One Week Late] 
FROM USERS u 
GROUP BY u.USER_NAME 
1
-- CASE is your friend. CASE inside an aggregate is best-friend 
-- Remember: aggregates ignore nulls 
SELECT u.USER_NAME As [User],  
COUNT(CASE ad.DAYS_LATE BETWEEN 1 and 7 AND ad.COMPLETED_DATE is NULL THEN ad.ACTIVITY_ID END) As [Upto One Week Late] 
COUNT(CASE WHEN ad.DAYS_LATE > 0 AND ad.COMPLETED_DATE THEN ad.ACTIVITY_ID END) As [Total Activities Late], 
FROM USERS u  
JOIN ACTIVITY_DATA ad 
ON u.USER_ID = ad.USER_ID 
GROUP BY u.USER_NAME 
相關問題