我有一个带有两列的sql Log表,如下所示:
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
,以便如果registrantid
适用于两个不同的公司,那么它将被添加两次,但如果{{1}多于一次然后它会被添加一次。以上数据应该是6.我需要使用group by吗?
请建议
答案 0 :(得分: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上设置一个工作示例 请让我知道你的想法。
答案 1 :(得分:2)
您可以在没有GROUP BY的情况下执行此操作,只需将COUNT替换为复数值的COUNT:
COUNT(DISTINCT CAST(RegistrantID as VARCHAR(100))
+'-'+CAST(CompanyID as VARCHAR(100))
) AS Counts