简体   繁体   English

SQL Server:连接和 where 子句

[英]SQL Server : concatenate and where clause

I am trying to concatenate three columns from two tables Customer and Invoice , create a new column and find the new_id member whose name begins from 'Astridgruber' in SQl Server.我试图连接来自两个表CustomerInvoice三列,创建一个新列并在 SQl Server 中找到名称以“Astridgruber”开头的 new_id 成员。

The below is causing an error.以下导致错误。

select 
    concat(c.FirstName, c.LastName, i.InvoiceId) as New_Id
from 
    Invoice i, Customer c
where 
    i.[CustomerId] = c.CustomerId 
where 
    New_Id = 'AstriGruber%'

Help will be much appreciated.帮助将不胜感激。

These are the tables from the Chinook Database:这些是来自 Chinook 数据库的表:

图片

Too long for a comment.评论太长了。 You have a few issues:你有几个问题:

  1. You should be using modern, explicit JOIN syntax, not comma joins;您应该使用现代的、显式的JOIN语法,而不是逗号连接;
  2. Too many WHERE clauses; WHERE子句太多; AND the conditions together; AND条件在一起;
  3. You can't use aliases in WHERE clauses;您不能在WHERE子句中使用别名; replace New_Id with concat(c.FirstName,c.LastName,i.InvoiceId) ;concat(c.FirstName,c.LastName,i.InvoiceId)替换New_Id
  4. You should be using LIKE , not =您应该使用LIKE ,而不是=

All up your query should look like:您的所有查询应如下所示:

select concat(c.FirstName,c.LastName,i.InvoiceId) as New_Id
from Invoice i
join Customer c on i.CustomerId = c.CustomerId 
where concat(c.FirstName,c.LastName,i.InvoiceId) LIKE 'AstriGruber%'

Demo on dbfiddle dbfiddle 上的演示

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

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