我试图获取某个列的计数(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`
答案 0 :(得分:0)
虽然您的查询不是那么清楚,但是根据我的理解,您需要这样的内容
SELECT COUNT(*) AS CountAll, COUNT(DISTINCT p.ref) AS CountDistinct
FROM ...