获取总计数和子集计数的最简单方法是什么?

时间:2010-12-11 00:47:38

标签: sql sql-server sql-server-2005

我试图这样做:

SELECT COUNT(*),
        (
            SELECT COUNT(*) FROM attend
            WHERE (DATEPART(WEEKDAY,start_date) = 2 OR DATEPART(WEEKDAY,start_date) = 6)
            AND empl_no = 12345
        )
        FROM attend as a
 WHERE empl_no = 12345

但这看起来有点难看。有更好的方法吗?

3 个答案:

答案 0 :(得分:10)

使用:

SELECT COUNT(*) AS total,
       SUM(CASE 
             WHEN DATEPART(WEEKDAY, t.start_date) IN (2,6) THEN 1 
             ELSE 0 
           END) AS weekday
  FROM ATTEND t
 WHERE t.empl_no = 12345

答案 1 :(得分:6)

您可以使用CTE

WITH T1 AS (
    SELECT DATEPART(WEEKDAY,start_date) AS weekday
    FROM attend
    WHERE empl_no = 12345
)
SELECT
    (SELECT COUNT(*) FROM T1) AS total,
    (SELECT COUNT(*) FROM T1 WHERE weekday = 2 OR weekday = 6) AS subset

答案 2 :(得分:0)

CUBEROLLUP对于一次性处理最终和中间聚合非常有用。对于这类问题,如果需要最终和中间总数,CUBE将是一个不错的选择,因此可以在没有来自源表的其他查询的情况下回答此问题和类似问题。我发现CUBE非常有用,可以避免往返DB。但是,在提前知道确切要求的情况下,单个聚焦选择(由@nate c很好地证明)是最有意义的。

DECLARE @T1 TABLE (total int, weekday int)

INSERT INTO @T1
SELECT COUNT(1), DATEPART(WEEKDAY,start_date)
FROM attend
WHERE empl_no = 12345
GROUP BY DATEPART(WEEKDAY,start_date) WITH CUBE

SELECT 
    (SELECT Total FROM @T1 WHERE weekday is NULL) AS total,
    (SELECT SUM(weekday) FROM @T1 WHERE weekday = 2 or weekday = 6) AS subset

-- continue using @T1 or a table variable was seriously overkill