我有两张桌子(User
和Salary
)。我想从left join
到User
进行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
答案 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
答案 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