简体   繁体   中英

Is it possible to return more then one row in sub-query

My Query

SELECT c.COLUMN_A,
(select count(b.COLUMN_B) from SAME_TABLE_NAME b where COLUMN_B='X' GROUP by   COLUMN_A) as ALIAS_NAME 

FROM SAME_TABLE_NAME c

Above query throw Error as

single-row sub query returns more than one row.

but i need all the row it is returning

Try:

    SELECT COLUMN_A, COUNT(COLUMN_B)  AS ALIAS_NAME 
      FROM SAME_TABLE_NAME 
      WHERE COLUMN_B='X' GROUP BY COLUMN_A

If that's not right, please post your real schema and an example of your data.

you are getting multiple results in your column. your looking for something like this.

select  COLUMN_A, count(b.COLUMN_B) from SAME_TABLE_NAME b 
            where COLUMN_B='X' GROUP by COLUMN_A

You may try this.

SELECT c.COLUMN_A,
(select count(b.COLUMN_B) from SAME_TABLE_NAME b 
 where COLUMN_B='X' 
 AND C.COLUMN_A=B.COLUMN_A   --- THIS WHERE CLAUSE IS ADDED TO MAP ALL YOUR COUNT RECORD WITH ITS RESPECTED COLUMN
 GROUP by B.COLUMN_A) as ALIAS_NAME 
FROM SAME_TABLE_NAME c

A scalar subquery should return at most one row. Hence, GROUP BY is not appropriate. If you want to express this using a subquery, you want a correlated subquery without GROUP BY :

SELECT c.COLUMN_A,
       (SELECT count(b.COLUMN_B) 
        FROM SAME_TABLE_NAME b 
        WHERE c.COLUMN_A = b.COLUMN_A AND
              b.COLUMN_B = 'X' 
       ) as ALIAS_NAME 
FROM SAME_TABLE_NAME c;

However, the better approach is to use window functions, available in the more recent versions of MySQL:

SELECT c.COLUMN_A,
       SUM(c.COLUMN_B = 'X') OVER (PARTITION BY c.COLUMN_A) as ALIAS_NAME 
FROM SAME_TABLE_NAME c;

Note that you should qualify all column references. This is especially true with subqueries, where the scoping rules may sometimes not do what you intend.

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