SQL Server:选择一列的计数,同时检查另一列中的不同值
Posted
技术标签:
【中文标题】SQL Server:选择一列的计数,同时检查另一列中的不同值【英文标题】:SQL Server : select count of one column, while checking for distinct value in another 【发布时间】:2017-05-29 17:55:45 【问题描述】:我正在尝试获取某个列 (sch1.[key]) 的计数,同时还要确保另一列具有不同的值 (p.[ref])。有没有一种简单的方法可以使用 SQL Server 完成此任务?
我认为答案在于加入 [test] 和 [person] 表
测试表:记录列将匹配人员表 id
id | record | value
----------------------------------
01 901 abc
02 902 def
03 903 ghi
这是我现在所拥有的,但交叉应用并没有删除重复项
declare @dataset_orgs uniqueidentifier = (select top 1 [id] from [dataset] where ([name] = 'Organizations'))
select
count(sch1.[key]) as [Total],
sch1.[key] as [CEEB],
sch1.[name] as [Institution],
sch1dadd.[region] as [Region],
(select [value] from dbo.getPromptTable(sch1dadd.[geomarket])) as [Geomarket],
(select [value] from dbo.getFieldTopTable(sch1d.[id], 'staff_assign')) as [Staff]
from [test] t
CROSS APPLY
(
select
DISTINCT p2.[id],
from [person] p2
where (p2.[id] = t.[record])
) p
inner join [lookup.test] lt on (lt.[id] = t.[type]) and (isnull(lt.[subtype], '') = isnull(t.[subtype], ''))
left outer join [school] sch1 on (sch1.[record] = p.[id]) and (sch1.[rank_overall] = 1)
left outer join [dataset.row] sch1d on (sch1d.[dataset] = @dataset_orgs) and (sch1d.[key] = sch1.[key])
left outer join [address] sch1dadd on (sch1dadd.[record] = sch1d.[id]) and (sch1dadd.[rank_overall] = 1)
where
(
(t.[type] IN ('SATI', 'SATR'))
and
(convert(date, t.[date]) between isnull('1/1/2015', '1/1/1900') and isnull('12/31/2015', '12/31/9999'))
and
(isnull(convert(varchar(1), t.[confirmed]), '2') IN ('1'))
)
group by sch1.[key], sch1.[name], sch1dadd.[region], sch1dadd.[geomarket], sch1d.[id]
order by [Total] DESC`
【问题讨论】:
【参考方案1】:虽然你的查询不是很清楚,但据我了解你想要这样的东西
SELECT COUNT(*) AS CountAll, COUNT(DISTINCT p.ref) AS CountDistinct
FROM ...
【讨论】:
以上是关于SQL Server:选择一列的计数,同时检查另一列中的不同值的主要内容,如果未能解决你的问题,请参考以下文章
SQL server select语句用于选择另一列的重复条目的ID
如何在表中指定基于 SQL Server 中另一列的计算列?