如何加入这两个SQL查询?

时间:2016-03-01 06:04:58

标签: mysql sql-server join

我正在使用MySQL和MSSql,我试图将这两个查询加在一起。

查询1

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

查询2

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

我已经看到你可以把它们当作两张桌子来加入它们,但我却无法让它起作用。我试图加入他们的方式我在尝试使用余额之和时尝试选择代表名字和姓氏时会出现汇总错误。

提前致谢!

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

试试这个:

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...

答案 3 :(得分:0)

试试吧

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

答案 4 :(得分:0)

 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