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 query 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 @!
Well, GROUP BY and DISTINCT have their own use. GROUP BY cannot replace DISTINCT in some situations and DISTINCT cannot take place of GROUP BY. It is as per your choice and situation how you are optimizing both of them and choosing where to use GROUP BY and DISTINCT.
DISTINCT combined with ORDER BY needs a temporary table in many cases. Because DISTINCT may use GROUP BY , learn how MySQL works with columns in ORDER BY or HAVING clauses that are not part of the selected columns. See Section 12.20.
Distinct is used to find unique/distinct records where as a group by is used to group a selected set of rows into summary rows by one or more columns or an expression. The functional difference is thus obvious. The group by can also be used to find distinct values as shown in below query.
We can use GROUP BY without specifying any aggregate functions in the SELECT list. However, the same result is usually produced by specifying DISTINCT instead of using GROUP BY. According to Tom Kyte the two approaches are effectively equivalent (see AskTom "DISTINCT VS, GROUP BY").
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With