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;
当前回答
这是一个简单的解决方法:
WITH cte AS /* Declaring a new table named 'cte' to be a clone of your table */
(SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY val1 DESC) AS rn
FROM MyTable /* Selecting only unique values based on the "id" field */
)
SELECT * /* Here you can specify several columns to retrieve */
FROM cte
WHERE rn = 1
其他回答
好问题@aryaxt——你可以看出这是一个好问题,因为你5年前问过这个问题,而我今天在试图找到答案时偶然发现了它!
我只是试图编辑接受的答案,以包括这一点,但如果我的编辑没有使它:
如果你的表不是那么大,并且假设你的主键是一个自动递增的整数,你可以这样做:
SELECT
table.*
FROM table
--be able to take out dupes later
LEFT JOIN (
SELECT field, MAX(id) as id
FROM table
GROUP BY field
) as noDupes on noDupes.id = table.id
WHERE
//this will result in only the last instance being seen
noDupes.id is not NULL
将GROUP BY添加到要检查重复的字段 您的查询可能看起来像
SELECT field1, field2, field3, ...... FROM table GROUP BY field1
将检查Field1以排除重复记录
或者你可能会问
SELECT * FROM table GROUP BY field1
字段1的重复记录被排除在SELECT中
SELECT * from table where field in (SELECT distinct field from table)
从您的问题措辞中,我了解到您希望为给定字段选择不同的值,并为每个这样的值列出同一行中的所有其他列值。大多数dbms不允许使用DISTINCT或GROUP BY,因为结果是不确定的。
可以这样想:如果field1出现了不止一次,那么将列出field2的值(假设在两行中field1的值相同,但在这两行中field2的值不同)。
然而,你可以使用聚合函数(显式地为你想要显示的每个字段),并使用GROUP BY而不是DISTINCT:
SELECT field1, MAX(field2), COUNT(field3), SUM(field4), ....
FROM table GROUP BY 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的每个不同组合进行行计数。