简体   繁体   English

是否有一种SQL语法会根据同一表中第3列的相等值搜索2列来创建新列?

[英]Is there a SQL syntax that will create new column by searching in 2 columns based on equal value of 3rd column in same table?

I have 1 table, with fields named: class_code, name1, class_code1, name2, class_code2. 我有1个表,其字段名为:class_code,name1,class_code1,name2,class_code2。 I would like to search the value of class_code, and display it as class_code and name only, where class_code = class_code1 or class_code = class_code2. 我想搜索class_code的值,并将其显示为class_code和仅名称,其中class_code = class_code1或class_code = class_code2。 The results will display class_code and name 结果将显示class_code和名称

Is this possible using sql join syntax? 是否可以使用sql join语法?

This is the table: 这是表:

    class_code  name1     class_code1   name2     class_code2
    C0001       John      C0002         Ben       C0001
    C0002       Ren       C0001         Elizh     C0002
    C0001       Jeff      C0001         Harry     C0001

The output I need is: 我需要的输出是:

    class_code        name
    C0001             Ben
    C0002             Elizh
    C0001             Jeff
    C0001             Harry

If the intention is that class_code1 and name1 should go together and class_code2 and name2 go together, you could do this with a UNION : 如果打算将class_code1和name1放在一起,将class_code2和name2放在一起,则可以使用UNION

SELECT class_code1 AS class_code, name1 AS name FROM table
UNION
SELECT class_code2 AS class_code, name2 AS name FROM table

If I got it right 如果我做对了

SELECT class_code, name1 
FROM tbl
WHERE class_code = class_code1 
UNION --ALL
SELECT class_code, name2
FROM tbl
WHERE class_code = class_code2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 取具有相同值 x 或不同值 x/y 的 2 列来创建具有值 x 的第 3 列 - Taking 2 columns with equal value x or differing values x/y to create a 3rd column with value x Pandas:如果来自第三列的字符串值,则根据另一列的值创建列 - Pandas : Create columns based on values of another column if string value from 3rd column 比较来自相同 pandas dataframe 的 2 列的值和基于比较的第 3 列的返回值 - comparing values of 2 columns from same pandas dataframe & returning value of 3rd column based on comparison 基于第三个值的 New_target 列 - New_target column based on 3rd value 查找 ia strn 列在同一数据框中的列表列中,并创建具有值的第三列 - Find ia a strn column is in a list column in the same data frame and create a 3rd column with a value Python 或 Excel:如何比较 2 列,然后在新列中写入第 3 列的值? - Python or Excel: How can you compare 2 columns and then write the value of a 3rd column in a new column? Python Pandas - 检查两列中的值,对第三列求和 - Python Pandas - check value in two columns, sum the 3rd column 根据 Python 中的第三列值设置 Plotly 条形颜色 - Set Plotly Bar Color Based on 3rd Column Value in Python 如果两列值相等,则在 Python 中创建具有 True 和 False 值的第三列 - if two column values are equal then create 3rd column which has True and False values in Python DataFrame:根据第 3 列中的值确定的动态列更新一列值 - DataFrame: update one column value based on dynamic column determined by value in 3rd column
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM