开发者

How to distinct the record when using Group By?

开发者 https://www.devze.com 2023-03-03 07:47 出处:网络
Hallo, I am having the table (look below), which having 4 records. Notice that ColumnA and ColumnB are having the same value, and ColumnC and columnD will have different value.

Hallo, I am having the table (look below), which having 4 records. Notice that ColumnA and ColumnB are having the same value, and ColumnC and columnD will have different value.

ColumnA ColumnB ColumnC ColumnD
------- ------- ------- -------
xx      yy      AAA     333
xx      yy      BBB     555
xx      yy      AAA     333
xx      yy      BBB     555

I was trying to select the whole record using Group By quer开发者_JS百科y like this:

SELECT ColumnC from TableA GROUP BY ColumnC;

This query only shows me ColumnC but my expectation is to select the whole record not only ColumnC.

UPDATE: My expected output is:

ColumnA ColumnB ColumnC ColumnD
------- ------- ------- -------
xx      yy      AAA     333
xx      yy      BBB     555

May I know how can I do this?

THanks @!


You could put all of the columns in your SELECT and GROUP BY clauses:

SELECT 
    ColumnA, ColumnB, ColumnC, ColumnD 
FROM 
    TableA 
GROUP BY
    ColumnA, ColumnB, ColumnC, ColumnD

This would basically be equivalent to

SELECT DISTINCT
    *
FROM
    TableA

but is more explicit. As has been pointed out by OMG Ponies, the syntax can vary between DBMSs. In some you may be able to simply do:

SELECT * FROM TableA GROUP BY ColumnC


In Oracle:

SELECT  *
FROM    (
        SELECT  t.*,
                ROW_NUMBER() OVER (PARTITION BY columnC ORDER BY columnA) AS rn
        FROM    mytable
        )
WHERE   rn = 1

Change the ORDER BY clause to control which of the records holding the duplicate will be returned (now that with the least value of columnA is).


If you are using MS SQL the following will get you what you need: SELECT ColumnC,* from TableA GROUP BY ColumnC;

in Oracle, I believe that select ColumnC, TableA.* from TableA GROUP BY COLUMNC; will get you there.


SELECT * from TableA GROUP BY ColumnC;


You would want to select all of the columns and you then need to group by with Column C being first: SELECT * FROM TableA GROUP BY ColumnC, ColumnA, ColumnB, ColumnD

0

精彩评论

暂无评论...
验证码 换一张
取 消