简体   繁体   中英

How do I join these two SQL queries?

I'm using MySQL and MSSql and I'm trying to join these two queries together.

Query 1

(SELECT REP.REP_NUM, REP.FIRST_NAME, REP.LAST_NAME
FROM REP, CUSTOMER)

Query 2

(SELECT CUSTOMER.REP_NUM, SUM(CUSTOMER.BALANCE) AS REP_BALANCE
FROM CUSTOMER
GROUP BY CUSTOMER.REP_NUM) 

I've seen you can treat these as two Tables and join them but I'm having trouble getting it to work. The way I was trying to join them I'd get aggregate errors from trying to select the rep first and last name while using the balance sum.

Thanks in advance!

SELECT R.REP_NUM, R.FIRST_NAME, R.LAST_NAME
FROM REP r
inner join
(SELECT c.REP_NUM, SUM(c.BALANCE) AS REP_BALANCE
FROM CUSTOMER c
GROUP BY c.REP_NUM) t
on r.rep_num = t.rep_num
SELECT r.REP_NUM, r.FIRST_NAME, r.LAST_NAME, SUM (c.BALANCE) AS REP_BALANCE
FROM   REP r
       INNER JOIN CUSTOMER c ON r.REP_NUM = c.REP_NUM
GROUP BY r.REP_NUM, r.FIRST_NAME, r.LAST_NAME

try this:

SELECT REP.REP_NUM, REP.FIRST_NAME, REP.LAST_NAME 
FROM REP join(
SELECT CUSTOMER.REP_NUM, SUM(CUSTOMER.BALANCE) AS REP_BALANCE 
FROM CUSTOMER 
GROUP BY CUSTOMER.REP_NUM
) as B on some_condition...

试试吧

select a.REP_NUM,a.FIRST_NAME,a.LAST_NAME,b.REP_NUM,Sum(b.BALANCE) as REP_BALANCE from REP a as inner join CUSTOMER b on a.REP_NUM=b.REP_NUM group by b.REP_NUM
 Select New.REP_NUM,New.FIRST_NAME,New.LAST_NAME,CUSTOMER.REP_NUM, 
    SUM(CUSTOMER.BALANCE) AS REP_BALANCE 
    from (SELECT REP.REP_NUM, REP.FIRST_NAME, REP.LAST_NAME
    FROM REP, CUSTOMER) New
    inner join CUSTOMER  ON CUSTOMER.REP_NUM=New.REP_NUM
    GROUP BY CUSTOMER.REP_NUM

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