您好,我需要一些 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 列中,我们有与客户关联的代码,这些代码从数字更改为字母数字。因此,我需要创建另一个查询来处理此结果(第一个查询的结果),以识别从旧代码迁移到新代码的所有客户。输出需要是这样的
oldCode currentCode oldType newType
jhk 1ab2 old new
ujy 45wr old new
谢谢
最佳答案
您可以在结果表上使用 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";
关于mysql - 需要弄清楚何时 和 ID 在 SQL 中关联有两个不同的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56906139/