Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query with subquery returning "single-row subquery returning more than one row"?

Tags:

sql

mysql

Here's my query:

SELECT TRANS_MSTR.branch_id
  FROM TRANS_MSTR, BRANCH_MSTR
 WHERE BRANCH_MSTR.branch_type_desc = 'ATM ONLY' 
   And ( SELECT SUM(TRANS_MSTR.trans_amount)  
           FROM TRANS_MSTR 
          WHERE TRANS_MSTR.trans_yyyymm = '201511' 
       GROUP BY TRANS_MSTR.branch_id) < 100;

"ORA-01427: single-row subquery returns more than one row"

is the error I get. I don't know really what that even means? The goal of my query overall is to return the branch ID and the sum, where sum is less than 100.

When I try to fix it like this:

     SELECT TRANS_MSTR.branch_id, 
           (SELECT SUM(TRANS_MSTR.trans_amount) 
              FROM TRANS_MSTR 
             WHERE TRANS_MSTR.trans_yyyymm = '201511' 
          GROUP BY TRANS_MSTR.branch_id) as TransAmt
              FROM TRANS_MSTR, BRANCH_MSTR
             WHERE BRANCH_MSTR.branch_type_desc = 'ATM ONLY' 
               And TransAmt < 100;

It tells me that TRANSAMT is an invalid identifier. But I thought you could alias subqueries?

like image 648
CapnShanty Avatar asked Nov 30 '25 16:11

CapnShanty


2 Answers

Please try this:

    SELECT BRANCH_MSTR.branch_id,  SUM(TRANS_MSTR.trans_amount) 
        AS TransAmt FROM BRANCH_MSTR b
INNER JOIN BRANCH_MSTR 
        ON TRANS_MSTR.branch_id = BRANCH_MSTR.branch_id 
     WHERE BRANCH_MSTR.branch_type_desc = 'ATM ONLY' 
       AND TRANS_MSTR.trans_amount < 100 
       AND TRANS_MSTR.trans_yyyymm = '201511' 
  GROUP BY TRANS_MSTR.branch_id;
like image 197
Pankaj Kumar Avatar answered Dec 02 '25 07:12

Pankaj Kumar


I think you want a correlated subquery:

SELECT b.branch_id
FROM BRANCH_MSTR b
WHERE b.branch_type_desc = 'ATM ONLY' and
      (SELECT SUM(t.trans_amount)
       FROM TRANS_MSTR t
       WHERE t.trans_yyyymm = '201511' AND
             t.branch_id = b.branch_id
      ) < 100;

This is not how I would write the query. But you have started down the path of using a subquery rather than JOIN/GROUP BY, which would be the more traditional approach.

like image 35
Gordon Linoff Avatar answered Dec 02 '25 05:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!