0

我加入了两个普遍的数据库。这两个数据库可能具有相同的社会安全号码。我正在尝试为这些多条记录中的每一条设置一条主记录。主记录应该是最早的 Orig_Hire 日期和 Active = 'A'

database_1.demographics
Ss_No        Orig_Hire    Active
111-00-1111  2015-01-01   A
111-00-1111  2014-01-01   T
111-00-1111  2015-08-07   A

database_2.demographics
Ss_No        Orig_Hire    Active
111-00-1111  2013-01-01   T
111-00-1111  2012-01-01   T

这是我的查询:

SELECT demo.*, 
(select (some logic) from demo WHERE GROUP BY Ss_No) As Primary_Record //this doesnt work
FROM
    (SELECT Ss_No, Orig_Hire, Active FROM database_1.demographics
    UNION ALL
    SELECT Ss_No, Orig_Hire, Active FROM database_2.demographics) demo

还有另一种更好的方法吗?

谢谢

4

2 回答 2

0

我通过使用 PHP 解决了这个问题。这是我想出的最简单的方法。

$sql = "SELECT Ss_No, Orig_Hire, Active FROM database_1.demographics
        UNION ALL
        SELECT Ss_No, Orig_Hire, Active FROM database_2.demographics
        ORDER BY 1,3,2 ASC"; /* ORDERBY is important since we are setting the first record*/

$sth = $apex->prepare($sql);
$sth->execute();

$sth->setFetchMode(PDO::FETCH_ASSOC);

$SSN = '';

foreach ($sth as $row) {
    if($row['SSN'] != $SSN) {
        $row['IsPrimaryAssignment'] = 1;
    } else {
        $row['IsPrimaryAssignment'] = 0;
    }
    $SSN = $row['SSN'];
}
于 2015-11-18T20:09:01.393 回答
0

您需要分两部分执行此操作。

首先找到最小值,然后获取与该最小值匹配的记录。

让您简化您致电工会的问题demo

SELECT Ss_No, Orig_Hire, Active FROM database_1.demographics
UNION ALL
SELECT Ss_No, Orig_Hire, Active FROM database_2.demographics

所以你找到MIN每个日期的逻辑SSN

SELECT Ss_No, MIN(Orig_Hire) as Orig_Hire    
FROM demo
WHERE Active = 'A'
GROUP BY Ss_No

现在你需要找到完整的记录。

SELECT demo.*
FROM demo
LEFT JOIN (
    SELECT Ss_No, MIN(Orig_Hire) as Orig_Hire    
    FROM demo
    WHERE Active = 'A'
    GROUP BY Ss_No
    ) min_hire
  ON demo.Orig_Hire = min_hire.Orig_Hire  
 AND demo.Ss_No = min_hire.Ss_No
  • 如果不存在MIN(Orig_Hire)Active = 'A'你会得到一些Ss_no空值,你应该验证这些。

  • 这也假设一个 Ss_No 没有多行相同MIN(Orig_Hire) and Active = 'A'

于 2015-11-17T17:36:16.670 回答