【发布时间】: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`
【问题讨论】:
标签: sql sql-server join distinct cross-apply