在count SQL中显示0

时间:2014-12-04 09:05:14

标签: sql sql-server sql-server-2008

这是我的结果:

Year    matches
2005    1
2008    2

这是我的预期结果:

Year    matches
2005    1
2006    0
2007    0
2008    2

这就是我的尝试:

SELECT DATEPART(yy,A.match_date) AS [Year], COUNT(A.match_id) AS "matches"
FROM match_record A
INNER JOIN match_record  B ON A.match_id = B.match_id
WHERE (score) IS NULL OR (score) = 0
GROUP BY DATEPART(yy,A.match_date);

我想在得分有一些值的年份中得到零作为计数(不为零和零,任何大于0的值)。有人能帮助我吗?

4 个答案:

答案 0 :(得分:0)

这可能会做你正在寻找的事情:

SELECT DATEPART(yy,A.match_date) AS [Year],
    SUM(CASE WHEN score=0 or score is null THEN 1 ELSE 0 END) AS "matches"
FROM match_record A
INNER JOIN match_record  B ON A.match_id = B.match_id
GROUP BY DATEPART(yy,A.match_date);

假设您在缺失的年份中有任何数据,现在应该会产生预期的结果。

相反,如果您需要0多年没有数据,那么您需要单独提供年份列表(例如,通过数字表格),然后{{1}这是您现有查询的来源。

答案 1 :(得分:0)

怎么样,

SELECT
            [year],
            COUNT(*) [matches]
    FROM (
            SELECT
                        DATEPART(yy, [A].[match_date]) [year]
                 FROM
                        [match_record] [A]
                     LEFT JOIN
                        [match_record] [B]
                            ON [A].[match_id] = [B].[match_id]
                 WHERE
                        COALESCE([B].[score], 0) = 0) [Nils]
    GROUP BY
            [Year];

答案 2 :(得分:0)

考虑以下是你的表

SELECT * INTO #TEMP FROM
(
    SELECT 2005 [YEARS],1 [MATCHES]
    UNION ALL
    SELECT 2008,2
)T

声明两个变量以获取表格中的最小和最大日期

DECLARE @MINYEAR int;
DECLARE @MAXYEAR int;
SELECT @MINYEAR = MIN(YEARS) FROM #TEMP
SELECT @MAXYEAR = MAX(YEARS) FROM #TEMP

执行以下recursion以获得表格中的句点与LEFT JOIN之间的年份。

; WITH  CTE as
(
    select  @MINYEAR as yr FROM #TEMP 
    UNION ALL
    SELECT YR + 1
    FROM    CTE
    WHERE   yr < @MAXYEAR
)
SELECT DISTINCT C.YR,CASE WHEN T.MATCHES IS NULL THEN 0 ELSE T.MATCHES END MATCHES 
FROM    CTE C
LEFT JOIN #TEMP T ON C.yr=T.YEARS

答案 3 :(得分:0)

DECLARE @t table(Year int,   matches  int)
DECLARE @i int=2005
WHILE @i <=2008
BEGIN
IF NOT exists (SELECT matches FROM tbl WHERE year=@i)
BEGIN
INSERT INTO @t
SELECT @i,'0'
SET @i=@i+1
END
else
BEGIN
INSERT INTO @t
SELECT  year,[matches] from tbl
SET @i=@i+1
END
END
SELECT DISTINCT * FROM @t

enter image description here