简体   繁体   English

如何添加新列并从其他列获取数据? SQL

[英]How to add new column and get the data from other column? SQL

You can see what I exactly mean on the image below. 您可以在下面的图片中看到我的确切意思。 I want to create new column " Bill To This Company " and get the company name from BillToCustomerID 我想创建新列“ 向该公司 开票 ”,并从BillToCustomerID获取公司名称

在此处输入图片说明

Could be you need a self join 您可能需要自我加入

select a.customerId, a.CustomerName, a.BillToCustomerId, b.CustmerName 
from my_table a 
inner join my_table  b on a.BillToCustomerId = b.customerId

Just self-join on the table and give that CustomerName an alias 只是在表上自我联接,并给CustomerName一个别名

select 
 c.CustomerId, 
 c.CustomerName, 
 c.BillToCustomerId, 
 b.CustomerName as "Bill To This Company"
from Customer c
left join Customer b on (b.CustomerId = c.BillToCustomerId)

Seems you need subquery : 似乎您需要subquery

select c.*,
       (select c1.CustomerName
        from Customer c1
        where c1.BillToCustomerId = c.BillToCustomerId
        order by c1.customerid 
        limit 1
       ) as BilltoThisCompany
from Customer c;
update tableName as t1 join tableName as t2 on t1.BillToCustomerID=t2.CustomerId
  set t1.`Bill To This Company` = t2.customerName;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM