需要弄清楚何时和ID在SQL中关联了两个不同的代码

时间:2019-07-05 15:52:39

标签: mysql sql cell

嗨,我需要SQL方面的帮助。

我有这样的查询

select sub.*
from(
    select 
        distinct columnA,   
        case
            'some logic that is working'
        end as ColumnB,
        columnC,    
        "ColumnD"
    from Table1
    where "ColumnD"::date = 'some date'
    UNION
    select 
        distinct columnA,   
        case
            'some logic that is working'
        end as ColumnB,
        columnC,    
        "ColumnD"
    from Table1
    where "ColumnD"::date = 'some date'
    ) sub
order by sub.columnC

                 Result 
   Column A  Column B  Column C  Column D  
       abc      old       a 
       abc      old       a
       jhk      old       b
       1ab2     new       b
       25sa     new       c
       24sb     new       d
       ujy      old       e
       45wr     new       e 

现在在A列中,我们有与客户关联的代码,这些代码已从数字更改为字母数字。因此,我需要创建另一个查询以处理该结果(firt查询的结果),以识别从旧代码迁移到新代码的所有客户。输出必须是这样的

    oldCode  currentCode  oldType  newType
      jhk       1ab2        old      new 
      ujy       45wr        old      new  

谢谢

1 个答案:

答案 0 :(得分:0)

您可以在结果表上使用SELF JOIN获得预期结果。

此外,您可以使用临时表存储复杂查询的结果,否则,对于简单查询,可以直接在第二个查询的FROM子句中使用第一个查询。

CREATE TEMPORARY TABLE test
SELECT * FROM tblname;   //this line you can write your first query 

CREATE TEMPORARY TABLE test_copy LIKE test;
INSERT INTO test_copy (SELECT * FROM test);

SELECT 
    t.ColumnA as oldCode,
    t1.ColumnA as newCode,
    t.ColumnB as oldType,
    t1.ColumnB as newType
FROM 
    test as t JOIN test_copy as t1
    ON t.ColumnC=t1.ColumnC
WHERE 
    t.ColumnB="old" AND t1.ColumnB="New";

DEMO