在我的办公室里,属于两个部门的是普通人。对于查询,我想限制它,以便每个人只与一个部门相关联。
例如,这里有两个HR表:
表1
ID | Last_Name | Department
--------------------------------
1 Doe Informatics
2 Miller Database Management
2 Miller Informatics
3 Johnson Engineering
4 Mitchell Database Management
4 Mitchell Engineering
表2
ID | Date_of_sale
--------------------------------
1 8-2-2012
1 1-4-2003
2 5-23-2000
2 1-17-2003
2 12-30-2001
2 9-8-2013
3 4-19-2013
4 3-8-2015
4 11-8-2013
4 2-12-2007
我想做类似的事情:
SELECT Last_Name, FIRST(Department), Date_of_Sale
From column1,
FROM column1 JOIN column2 ON column1.id=column2.id
GROUP BY Last_Name
哪会回来:
Last_Name | Department | Date_of_sale
----------------------------------------
Doe Informatics 8-2-2012
Doe Informatics 1-4-2003
Miller Database Management 5-23-2000
Miller Database Management 1-17-2003
Miller Database Management 12-30-2001
Miller Database Management 9-8-2013
Johnson Engineering 4-19-2013
Mitchell Database Management 3-8-2015
Mitchell Database Management 11-8-2013
Mitchell Database Management 2-12-2007
每个人现在只有一个部门与他们相关联。
答案 0 :(得分:1)
不知道你的RDBMS提供具体答案并不容易。在大多数系统中,一般的答案是使用带聚合的嵌套选择:
SELECT c1.ID, c1.Last_name, c1.Department, c2.Date_of_Sale
FROM
(SELECT
ID
,Last_name
,MIN(Department) as Department
FROM
column1
GROUP BY
ID
,Last_name) c1
INNER JOIN column2 c2
ON c1.ID = c2.ID
然后在SQL-SERVER和大多数支持公用表表达式和窗口函数的其他RDBMS上,你可以创建一个分区的ROW_NUMBER()来选择你想要的东西(注意cte也可以是嵌套的选择。
;WITH cte AS (
SELECT
*
,ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Department) as RowNumber
FROM
column1
)
SELECT
c1.Id
,c1.Last_name
,c1.Department
,c2.Date_of_Sale
FROM
cte c1
INNER JOIN column2 c2
ON c1.Id = c2.Id
WHERE
c1.RowNumber = 1
这是一种典型的做法,如果你以某种方式对你将返回哪个部门进行优先考虑,例如:记录创建日期......但是如果支持窗口功能,并且您不关心哪个部门可以获取分区的MIN()或MAX(),这只是1 select语句中记录的升序。
SELECT DISTINCT
c1.ID
,c1.Last_name
,MIN(c1.Department) OVER (PARTITION BY c1.ID) as Department
,c2.Date_of_Sale
FROM
column1 c1
INNER JOIN column2 c2
ON c1.ID = c2.ID
答案 1 :(得分:1)
有几种方法可以执行此操作,具体取决于您使用的SQL类型以及您希望如何为每个姓氏选择部门。
以下是使用 MySQL 的几个示例。
选择首先列出的部门:
SELECT id, last_name,
SUBSTRING_INDEX(GROUP_CONCAT(department), ',', 1) AS Department
FROM column1
GROUP BY id, last_name
按字母顺序选择部门:
SELECT id, last_name, MIN(department)
FROM column1
GROUP BY id, last_name
答案 2 :(得分:1)
使用子查询获取每个用户的第一个部门,然后加入第二个表:
SELECT t1.Last_Name,
t1.Department,
t2.Date_of_Sale
FROM (select id, Last_Name, MIN(Department) Department from column1 group by id, Last_Name) t1
JOIN column2 t2 ON
t1.id = t2 .id