简体   繁体   中英

How to select rows based on unique column

I have table with values as

ColumnA   ColumnB

    ASD       A
    CSD       B
    DSD       C
    ESD       D
    FSD       D
    GSD       D

Column A is primary key, I need result as

ColumnA   ColumnB

    ASD       A
    CSD       B
    DSD       C
    ESD       D

I want all unique values from column B & their associated first values columnA.

I tried few queries & looked on Google but couldn't find ant solution .

Thanks, Rohit.

First is First in key order (ie alphabetically).

SELECT MIN(ColumnA) AS ColumnA, ColumnB
FROM tbl
GROUP BY ColumnB

You've tagged both MySQL and Oracle for some reason. The above will work in both.

Oracle also has analytical functions that can help with this general type of query.

select min(columna) columna, columnb
from mytable
group by columnb;

With analytics (Oracle):

SQL> WITH tab AS (
  2     SELECT 'ASD' columnA, 'A' columnB FROM DUAL
  3     UNION ALL SELECT 'CSD', 'B' FROM DUAL
  4     UNION ALL SELECT 'DSD', 'C' FROM DUAL
  5     UNION ALL SELECT 'ESD', 'D' FROM DUAL
  6     UNION ALL SELECT 'FSD', 'D' FROM DUAL
  7     UNION ALL SELECT 'GSD', 'D' FROM DUAL
  8  )
  9  SELECT columnA, columnB
 10    FROM (SELECT columnA, columnB,
 11                 rank() over(PARTITION BY columnB ORDER BY columnA) rnk
 12            FROM tab)
 13   WHERE rnk = 1;

COLUMNA COLUMNB
------- -------
ASD     A
CSD     B
DSD     C
ESD     D
select min(ColumnA) as ColumnA,ColumnB from table
group by ColumnB
CREATE TABLE #t_Val
(
    ColumnA VARCHAR(3) PRIMARY KEY
,   ColumnB CHAR(1) NOT NULL
)

INSERT #t_Val
SELECT 'ASD' ,  'A'
UNION
SELECT 'CSD' ,  'B'
UNION
SELECT 'DSD' ,  'C'
UNION
SELECT 'ESD' ,  'D'
UNION
SELECT 'FSD' ,  'D'
UNION
SELECT 'GSD' ,  'D'


SELECT  MIN(ColumnA),ColumnB
FROM #t_Val
GROUP BY ColumnB

Just another way of doing the same thing:

SELECT DISTINCT
    FIRST_VALUE(ColumnA)
    OVER (PARTITION BY ColumnB
          ORDER BY ColumnA) AS ColumnA,
    ColumnB
FROM tbl

This has the advantage of being usable with more than one column (ie where the GROUP BY method doesn't work).

Here is solution

CREATE TABLE tbl_test ( col1 varchar(5) collate latin1_general_ci NOT NULL, col2 varchar(5) collate latin1_general_ci NOT NULL, PRIMARY KEY ( col1 ) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

INSERT INTO tbl_test VALUES ('ASD', 'A'); INSERT INTO tbl_test VALUES ('CSD', 'B'); INSERT INTO tbl_test VALUES ('DSD', 'C'); INSERT INTO tbl_test VALUES ('ESD', 'D'); INSERT INTO tbl_test VALUES ('FSD', 'D'); INSERT INTO tbl_test VALUES ('GSD', 'D');


SELECT DISTINCT ( col2 ), col1 FROM tbl_test GROUP BY col2 LIMIT 0 , 30;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM