SQL Server COUNT问题 - 未显示零计数

时间:2018-01-27 20:34:54

标签: sql-server tsql count

我正在尝试运行我认为简单的COUNT查询,尽管我对COUNT并不是很精通。

我正在跑步:

SELECT SourceID, COUNT(*) as SourceCount
FROM dbo.Capture
WHERE SourceID in (37, 38, 130, 131, 132, 133)
GROUP BY SourceID

此查询的结果仅显示SourceID的COUNT大于零记录的行。如何让结果显示所有那些SourceID,包括没有计数的那些,我希望在SourceCount列中看到零或NULL,并不重要。

感谢。

3 个答案:

答案 0 :(得分:2)

SELECT val.id, COUNT(*) as SourceCount
FROM (values (37), (38), (130), (131), (132), (133)) val(id)
LEFT JOIN dbo.Capture
  on SourceID = val.id
GROUP BY val.id

答案 1 :(得分:1)

试试这个:

SELECT SourceID, COUNT(*) AS SourceCount FROM dbo.Capture
WHERE SourceID IN (37, 38, 130, 131, 132, 133)
GROUP BY SourceID
UNION
SELECT *,0 FROM dbo.Split('137, 38, 130, 131, 132, 133',',')
WHERE item NOT IN (SELECT SourceID FROM dbo.Capture WHERE SourceID IN (37, 38, 130, 131, 132, 133))

以下是dbo.Split函数的源代码:

CREATE FUNCTION [dbo].[Split] (@InputString VARCHAR(8000),@Delimiter VARCHAR(50))
RETURNS @Items TABLE (Item VARCHAR(8000))
AS
BEGIN
      IF @Delimiter = ' '
      BEGIN
            SET @Delimiter = ','
            SET @InputString = REPLACE(@InputString, ' ', @Delimiter)
      END

      IF (@Delimiter IS NULL OR @Delimiter = '')
            SET @Delimiter = ','

      DECLARE @Item           VARCHAR(8000)
      DECLARE @ItemList       VARCHAR(8000)
      DECLARE @DelimIndex     INT

      SET @ItemList = @InputString
      SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
      WHILE (@DelimIndex != 0)
      BEGIN
            SET @Item = SUBSTRING(@ItemList, 0, @DelimIndex)
            INSERT INTO @Items VALUES (@Item)

            SET @ItemList = SUBSTRING(@ItemList, @DelimIndex+1, LEN(@ItemList)-@DelimIndex)
            SET @DelimIndex = CHARINDEX(@Delimiter, @ItemList, 0)
      END -- End WHILE

      IF @Item IS NOT NULL -- At least one delimiter was encountered in @InputString
      BEGIN
            SET @Item = @ItemList
            INSERT INTO @Items VALUES (@Item)
      END

      -- No delimiters were encountered in @InputString, so just return @InputString
      ELSE INSERT INTO @Items VALUES (@InputString)

      RETURN

END -- End Function

答案 2 :(得分:0)

尝试子查询

Compare