左连接没有右表的多行

时间:2015-05-15 09:44:22

标签: sql sql-server teradata

我有两张桌子(UserSalary)。我想从left joinUser进行Salary。对于每个用户,我想要他们的名字和工资。如果他们没有工资,那么该领域可以留空。到目前为止,我们需要的是左连接。但我只想要每个用户一行。由于某些缺陷,一个用户可以有几个工资(见表薪水)。我只想要每个用户一行,可以随机选择(或者前1名)。我怎么做?预期的输出显示在底部。

用户表:

User Name
1    Adam
2    Al
3    Fred

薪资表

User  Salary
1     1000
2     2000
2     2000

预期表格:

User Name  Salary
1    Adam  1000
2    Al    2000 
3    Fred  null

5 个答案:

答案 0 :(得分:5)

试试这个:

select U.User, U.Name, min(S.Salary)
from UserTable U
left join SalaryTable S on S.User = U.User
group by U.User, U.Name

答案 1 :(得分:5)

User更改为Userid,因为User是SQL中的保留字

SELECT u.Userid, u.Name, MAX(S.Salary)
FROM Usertable u
LEFT JOIN Salarytable s ON u.Userid = s.userid
GROUP BY u.userid, u.name

SQL小提琴:http://sqlfiddle.com/#!6/ce4a8/1/0

答案 2 :(得分:1)

使用派生表从工资表中获取不同的行。

select u.userid, u.username, s.salary
from users u left join (select distinct userid, salary from salaries) s
  on u.userid = s.userid

此外,重命名表和列。表名通常应以s结尾(因为复数。)列不应该。

或者,执行GROUP BY

select u.userid, u.username, max(s.salary)
from users u left join salaries s
  on u.userid = s.userid
group by u.userid, u.username

或者跳过左连接,而是执行相关的子查询:

select u.userid, u.username, (select max(s.salary) from salaries s
                              where u.userid = s.userid)
from users

答案 3 :(得分:1)

您可以使用ROW_NUMBER获得最高(或最低)薪水:

SELECT *
FROM Usertable u
LEFT JOIN
 (
   select Userid, Salary,
      row_number() 
      over (partition by Userid
            order by Salary desc) as rn
   from Salarytable
 ) as s 
ON u.Userid = s.userid
AND rn = 1

在Teradata中,您可以在派生表中使用QUALIFY应用rn = 1过滤器:

SELECT *
FROM Usertable u
LEFT JOIN
 (
   select Userid, Salary,
      row_number() 
      over (partition by Userid
            order by Salary desc) as rn
   from Salarytable
   qualify rn = 1
 ) as s 
ON u.Userid = s.userid

答案 4 :(得分:0)

试试这个

 select distinct U.User, U.Name, S.Salary
 from UserTable U
 left join SalaryTable S on S.User = U.User