如何在COUNT()

时间:2016-11-18 06:29:23

标签: sql-server

我有1个包含票据信息的表,第二个包含知识文章信息。 门票可以链接到相应的知识文章。

在故障单表(IncidentsM1)中是一个CBA_KPF_ID列,它将包含一个文章ID或一个NULL。

我需要知道每篇文章的链接次数,即使它是0。

表格(编辑):

  • INCIDENTSM1 - 票证表
    • INCIDENT_ID - 故障单ID
    • CBA_KPF_ID - 文章ID
  • KMDOCUMENTM1 - 文章表
    • ID - 文章ID

如果我使用以下代码,我会得到除0链接之外的链接数:

SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID

其中一个结果是ID值为NULL,并且没有链接到商品的门票数量。

如果我使用以下(来自其他question)代码,我会得到一个文章列表,其中count为1或0,文章ID出现在多行中:

SELECT SD.CBA_KPF_ID, ISNULL(KM."Count", 0) FROM
(SELECT CBA_KPF_ID FROM INCIDENTSM1) SD
LEFT JOIN
(SELECT ID, count(ID) as "Count" FROM KMDOCUMENTM1 GROUP BY ID) KM
ON SD.CBA_KPF_ID=KM.ID
ORDER BY "Count" DESC

即使数字为0,是否可以获取文章列表以及链接的次数?

编辑:

我已经尝试了以下两个答案,但他们要么没有按ID分组,要么仍未显示0值。

我只是尝试生成没有0值的列表,然后联合一个表,其中所有ID都不在第一个语句中:

(SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID)

UNION

SELECT KM.ID, 0
FROM KMDOCUMENTM1 AS KM

WHERE KM.ID NOT IN (
SELECT A.ID FROM
(SELECT KM1.ID, COUNT(*) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID GROUP BY KM1.ID) A
)
ORDER BY "Count" DESC

问题在于UNION下方的所有内容似乎都没有返回任何内容。

3 个答案:

答案 0 :(得分:0)

假设您有以下表格:

DECLARE @DataSource01 TABLE
(
    [ID] TINYINT
   ,[RefID] TINYINT
);

DECLARE @DataSource02 TABLE
(
    [RefID] TINYINT
);

INSERT INTO @DataSource01 ([ID], [RefID])
VALUES (1, 1)
      ,(1, 2)
      ,(1, 3)
      ,(2, NULL)
      ,(2, NULL)
      ,(3, 1)
      ,(3, 2)
      ,(3, NULL);

INSERT INTO @DataSource02 ([RefID])
VALUES (1), (2), (3);

数据是:

SELECT *
FROM @DataSource01 DS1
LEFT JOIN @DataSource02 DS2
    ON DS1.[RefID] = DS2.[RefID];

enter image description here

所以,我猜你需要记录1的数量为3,记录2的数量为0,记录3的数量为2:

SELECT DS1.[ID]
      ,SUM(IIF(DS2.[RefID] IS NULL, 0, 1))
FROM @DataSource01 DS1
LEFT JOIN @DataSource02 DS2
    ON DS1.[RefID] = DS2.[RefID]
GROUP BY DS1.[ID]

enter image description here

注意,如果SQL Server版本不支持IIF函数,则可以使用CASE WHEN表达式更改它。

答案 1 :(得分:0)

试试这个

SELECT KM1.ID,IFF(COUNT(*) is null,0,1) AS "Count"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID

答案 2 :(得分:0)

如果计算非空左侧,则应计算行数,如果计算右侧,则应仅计算匹配

SELECT KM1.ID, COUNT(SD.CBA) AS CountAll, COUNT(KM1.ID) AS "CountMatches"
FROM INCIDENTSM1 AS SD LEFT JOIN KMDOCUMENTM1 AS KM1 ON SD.CBA_KPF_ID=KM1.ID
GROUP BY KM1.ID