1

我有一个带有两列的 sql 日志表,如下所示:

RegistrantID   compnayID 

1                1
1                1
2                1
3                1
1                2
2                2
2                2
3                2

我正在使用以下查询来获取唯一RegistrantID的 s

    SELECT 'Number of unique Profile views' AS Data, 
           4 AS Action,
           COUNT(DISTINCT RegistrantID) AS Counts
     FROM dbo.hr_ActionLog 
    WHERE Action = 4 
       AND (@DateFrom IS NULL OR dbo.DateOnly(ActionDate) >= dbo.DateOnly(@DateFrom))
       AND (@DateTo IS NULL OR dbo.DateOnly(ActionDate) <= dbo.DateOnly(@DateTo))
       AND (@CompanyID IS NULL OR CompanyID = @CompanyID)
       AND (@RegistrantID IS NULL OR RegistrantID = @RegistrantID)
       AND (@VacancyID IS NULL OR VacancyID = @VacancyID)

但是现在我想RegistrantId按公司获得唯一的 s ,这样如果 aregistrantid代表两个不同的公司,那么它将被添加两次,但如果 a 不止一次companyid,那么它将被添加一次。以上数据计数应为 6。我需要使用 group by 吗?

请建议

4

2 回答 2

4

尝试这个:

SELECT 'Number of unique Profile views'                AS Data, 
       4                                               AS Action, 
       Count(DISTINCT Cast(REGISTRANTID AS VARCHAR(5)) + '-' 
                      + Cast(COMPNAYID AS VARCHAR(5))) AS Counts 
FROM   DBO.HR_ACTIONLOG 

通过COUNT连接两列,我们可以计算两列之间唯一行的数量。

我删除了 WHERE 条件,以便可以在SQL Fiddle上设置一个工作示例。
请让我知道你的想法。

于 2013-08-15T07:43:57.193 回答
2

您可以在没有 GROUP BY 的情况下执行此操作,只需将您的 COUNT 替换为 COUNT 复杂值,例如:

COUNT(DISTINCT CAST(RegistrantID as VARCHAR(100))
              +'-'+CAST(CompanyID as VARCHAR(100)) 
) AS Counts
于 2013-08-15T07:44:52.710 回答