-1

I'm trying to get the count of a certain column (sch1.[key]), while also making sure another column has distinct values (p.[ref]). Is there an easy way to accomplish this with SQL Server?

I think the answer lies somewhere in joining the [test] and [person] tables

Test table: the record column will match on the person table id

id     |    record    |   value
----------------------------------
01           901          abc
02           902          def
03           903          ghi

Here is what I have right now, but the cross apply isn't removing the duplicates

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`
noot
  • 103
  • 1
  • 11

1 Answers1

0

although your query is not that clear, but from what I understood you want something like this

SELECT COUNT(*) AS CountAll, COUNT(DISTINCT p.ref) AS CountDistinct
FROM ...
asmgx
  • 7,328
  • 15
  • 82
  • 143