如何在SQL Server中使用DISTINCT
关键字?我的意思是它是否适用于特定领域。
select id, name, age
from dbo.XXX
查询返回了多行。我想知道有多少种身份证或姓名或年龄。
select **distinct** id, name, age from dbo.XXX
或
select id, **distinct** name, age from dbo.XXX
或
select id, name, **distinct** age from dbo.XXX
总而言之,我想使用单个SQL来获取每个字段的不同计数,例如select id, name, age from dbo.XXX
答案 0 :(得分:1)
Dense_Rank可用于计算任何列和多列的不同计数:
Select col1, col2, col3,
dense_rank() over (partition by [col1] order by [Unique ID]) + dense_rank() over (partition by [col1] order by [Unique ID] desc) - 1 as DistCountCol1,
dense_rank() over (partition by [col2] order by [Unique ID]) + dense_rank() over (partition by [col2] order by [Unique ID] desc) - 1 as DistCountCol2,
dense_rank() over (partition by [col3] order by [Unique ID]) + dense_rank() over (partition by [col3] order by [Unique ID] desc) - 1 as DistCountCol3
from [table]
答案 1 :(得分:0)
select distinct ID
from dbo.XXX
Select distinct name
from dbo.XXX
Select distinct age
from dbo.XXX
如果您想知道每个不同的ID或名称或年龄有多少行,您可以使用以下内容:
Select ID, count(id) as [ID_Recurrence]
from dbo.XXX
group by ID
Select Age, count(age) as [Age_Recurrence]
from dbo.XXX
group by Age
Select Name, count(name) as [Name_Recurrence]
from dbo.XXX
group by Name
答案 2 :(得分:0)
DISTINCT关键字返回一个唯一的行,如下面的
SELECT DISTINCT ID FROM SomeTable
SELECT DISTINCT ID , SCORE FROM SomeTable
如果您想从行获取唯一值,请尝试以下代码。
以下代码是从here
复制而来的select t.id, t.player_name, t.team
from tablename t
join (select team, min(id) as minid from tablename group by team) x
on x.team = t.team and x.minid = t.id
答案 3 :(得分:0)
select COUNT(distinct id) uniqueIDCount
from dbo.XXX
将计算id
字段的不同值,如果要计算字段组合的不同值,则必须连接字段,假设id
为整数且name
为nvarchar:
select COUNT(distinct CONVERT(nvarchar, id) + name) uniqueIDCount
from dbo.XXX
请注意,即使这种方式看起来不错,它可能不是最有效的方法,在这里你有更高效,但也更复杂的方法:
with c as (
select distinct id, name
from dbo.XXX
)select COUNT(1)
from c
答案 4 :(得分:0)
不确定为什么它很复杂。你可以有3个不同的查询,如果你愿意,你可以联合返回单集。