简体   繁体   中英

Invalid expression in the select list when using group by

I have the following query:

SELECT
  CU.EXCH_DENOM, CU.FRGN_AMOUNT
FROM
  CASHUP CU

Which returns a tables that looks as follows:

CU.EXCH_DENOM would be the currency type (USD, EURO) etc with CU.FRGN_AMOUNT being the actual amount in the respective currencies. In order to summarise the total per currency (similiar to a pivot table), I have changed by query as follows:

SELECT
  CU.EXCH_DENOM, CU.FRGN_AMOUNT
FROM
  CASHUP CU
GROUP BY
  CU.EXCH_DENOM

I am however getting a "invalid expression in the select list" error. I have used the group by function previously to perform the exact same thing in much more complex queries with no issues.

Any idea where I am going wrong?

You need to use an aggregation function, presumably SUM() :

SELECT CU.EXCH_DENOM, SUM(CU.FRGN_AMOUNT)
FROM CASHUP CU
GROUP BY CU.EXCH_DENOM

This works and remove duplicate values.

SELECT
  CU.EXCH_DENOM,CU.FRGN_AMOUNT
FROM
  CASHUP CU
GROUP BY
  CU.EXCH_DENOM,CU.FRGN_AMOUNT

GROUP BY is probably one of the concepts that confuse people most when starting out with SQL, so you are far from alone getting into trouble. Lets for simplicity assume the following table:

CREATE TABLE T
( a int not null
, b int not null
);

INSERT INTO T (a,b) VALUES (1,1), (1,2);

What would the following mean?

SELECT a, b
FROM T
GROUP BY a

In the group determined by a we have two different values for b , namely 1 and 2. Which row should be returned:

(1,1) or (1,2)?

So the query does not uniquely define a result. Older versions of MySQL (with default setting) would by default accept the query, and randomly pick one of these rows. All other DBMS that I know of does not accept the query. You can either add all columns not part of an aggregate, to your GROUP BY like saravanatn does:

SELECT a, b
FROM T 
GROUP BY a, b

which is the same as:

SELECT DISTINCT a, b
FROM T

or add an aggregate function for b as Gordon Linoff does in his answer:

SELECT a, SUM(b)
FROM T
GROUP BY a 

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