Let's say I have a table of customer addresses:
+-----------------------+------------------------+
| CName | AddressLine |
+-----------------------+------------------------+
| John Smith | 123 Nowheresville |
| Jane Doe | 456 Evergreen Terrace |
| John Smith | 999 Somewhereelse |
| Joe Bloggs | 1 Second Ave |
+-----------------------+------------------------+
In the table, one customer like John Smith can have multiple addresses. I need the SELECT
query for this table to return only first row found where there are duplicates in 'CName'. For this table it should return all rows except the 3rd (or 1st - any of those two addresses are okay but only one can be returned).
Is there a keyword I can add to the SELECT
query to filter based on whether the server has already seen the column value before?
7条答案
按热度按时间nzrxty8p1#
A very simple answer if you say you don't care which address is used.
If you want the first according to, say, an "inserted" column then it's a different query
zzoitvuj2#
In SQL 2k5+, you can do something like:
x6h2sr283#
You can use the
row_number() over(partition by ...)
syntax like so:What this does is that it creates a column called
row
, which is a counter that increments every time it sees the sameCName
, and indexes those occurrences byAddressLine
. By imposingwhere row = 1
, one can select theCName
whoseAddressLine
comes first alphabetically. If theorder by
wasdesc
, then it would pick theCName
whoseAddressLine
comes last alphabetically.pxiryf3j4#
You can use
row_number()
to get the row number of the row. It uses theover
command - thepartition by
clause specifies when to restart the numbering and theorder by
selects what to order the row number on. Even if you added anorder by
to the end of your query, it would preserve the ordering in theover
command when numbering.hc2pp10m5#
This will give you one row of each duplicate row. It will also give you the bit-type columns, and it works at least in MS Sql Server.
If you want to find all the duplicates instead, just change the rn= 1 to rn > 1. Hope this helps
uujelgoq6#
h5qlskok7#
to get every unique value from your customer table, use
more in-depth of w3schools: https://www.w3schools.com/sql/sql_distinct.asp