我在下面有一个查询,从我们的数据库中获取客户信息以发送优惠券。关于邮政编码,我们只想要该字段的前5位数...如何只返回前5位?我的代码如下:
SELECT Invoice_Tb.Customer_First_Name AS firstname, Invoice_Tb.Customer_Last_Name AS lastname, Invoice_Tb.Customer_Address AS add1, Invoice_Tb.City,
Invoice_Tb.Customer_State AS State, Invoice_Tb.ZIP_Code AS ZIP, Invoice_Tb.Customer_Email_Address AS [Email Address],
Invoice_Tb.Vehicle_Mileage AS [Vehicle Mileage], Invoice_Tb.Invoice_Date AS [Date Of Service], Invoice_Tb.Store_Number, @startdate AS Start_Date, @enddate AS End_Date
FROM Invoice_Detail_Tb INNER JOIN
Invoice_Tb ON Invoice_Detail_Tb.Invoice_Number = Invoice_Tb.Invoice_Number AND Invoice_Detail_Tb.Invoice_Date = Invoice_Tb.Invoice_Date
WHERE (Invoice_Detail_Tb.Store_Category_Code = 'FS') AND (Invoice_Tb.Invoice_Date BETWEEN CONVERT(DATETIME, @startdate, 102) AND CONVERT(Datetime,
@enddate, 102)) AND (Invoice_Tb.Reminder_Mail_Flag = 'Y')
答案 0 :(得分:3)
尝试
LEFT(FieldName, 5)
e.g。
SELECT LEFT(FieldName, 5) as SomeAlias FROM SomeTable
表:
FieldName
---------
Hello World
结果:
SomeAlias
---------
Hello
答案 1 :(得分:0)
如果您的字段是Invoice_Tb.ZIP_Code,则可以使用子字符串函数:
substring(Invoice_Tb.ZIP_Code, 1, 5) AS 'Trimmed Zip Code'
另一种选择是使用LEFT功能:
LEFT(Invoice_Tb.ZIP_Code, 5) AS 'Trimmed Zip Code'
由于存在从整数到nvarchar和nvarchar等效的隐式转换,因此无需担心在此处执行CAST。