简体   繁体   中英

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

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?

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.

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;

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