SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
当前回答
对于SQL Server,您可以使用dense_rank和其他窗口函数来获取指定列上具有重复值的所有行和列。这里有一个例子……
with t as (
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r1' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r2' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r3' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r4' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r5' union all
select col1 = 'a', col2 = 'a', col3 = 'a', other = 'r6'
), tdr as (
select
*,
total_dr_rows = count(*) over(partition by dr)
from (
select
*,
dr = dense_rank() over(order by col1, col2, col3),
dr_rn = row_number() over(partition by col1, col2, col3 order by other)
from
t
) x
)
select * from tdr where total_dr_rows > 1
这是对col1、col2和col3的每个不同组合进行行计数。
其他回答
只需将所有字段包含在GROUP BY子句中。
如果我没理解错的话,你的问题和我刚才遇到的问题很相似。您希望能够将DISTINCT的可用性限制在指定的字段,而不是将其应用于所有数据。
如果你使用GROUP BY而没有聚合函数,你GROUP BY的字段将是你的DISTINCT字段。
如果你有疑问:
SELECT * from table GROUP BY field1;
它将显示基于field1的单个实例的所有结果。
例如,如果您有一个包含名称、地址和城市的表。一个人有多个地址记录,但你只想要这个人的一个地址,你可以这样查询:
SELECT * FROM persons GROUP BY name;
结果将是该名称的一个实例及其地址将出现,而另一个实例将从结果表中被省略。注意:如果你的字段有原子值,如firstName, lastName,你想要分组。
SELECT * FROM persons GROUP BY lastName, firstName;
因为如果两个人有相同的姓氏,而你只按姓氏分组,那么其中一个人将从结果中被忽略。你需要考虑到这些事情。希望这能有所帮助。
SELECT c2.field1 ,
field2
FROM (SELECT DISTINCT
field1
FROM dbo.TABLE AS C
) AS c1
JOIN dbo.TABLE AS c2 ON c1.field1 = c2.field1
对于SQL Server,您可以使用dense_rank和其他窗口函数来获取指定列上具有重复值的所有行和列。这里有一个例子……
with t as (
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r1' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r2' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r3' union all
select col1 = 'a', col2 = 'b', col3 = 'c', other = 'r4' union all
select col1 = 'c', col2 = 'b', col3 = 'a', other = 'r5' union all
select col1 = 'a', col2 = 'a', col3 = 'a', other = 'r6'
), tdr as (
select
*,
total_dr_rows = count(*) over(partition by dr)
from (
select
*,
dr = dense_rank() over(order by col1, col2, col3),
dr_rn = row_number() over(partition by col1, col2, col3 order by other)
from
t
) x
)
select * from tdr where total_dr_rows > 1
这是对col1、col2和col3的每个不同组合进行行计数。
SELECT DISTINCT FIELD1, FIELD2, FIELD3 FROM TABLE1,如果这三列的值在表中都是唯一的。
例如,如果您的名字有多个相同的值,但所选列中的姓和其他信息不同,则该记录将包含在结果集中。