将sql查询结果的前4个字符分配到另一列?

时间:2015-05-26 14:08:57

标签: mysql sql

我使用下面的SQL代码来获取计算机列表。我需要以某种方式获取这些结果并在其旁边填充另一列,只包含每条记录的前4个字符。例如:

Computer Name  New Column

ABCD1000P      ABCD

这可能吗?

SELECT   SYS.Netbios_Name0
FROM dbo.v_R_System AS SYS 
     INNER JOIN dbo.v_GS_PROCESSOR AS Processor ON SYS.ResourceID = Processor.ResourceID 
     INNER JOIN dbo.v_GS_COMPUTER_SYSTEM ON SYS.ResourceID = dbo.v_GS_COMPUTER_SYSTEM.ResourceID
WHERE (SYS.Obsolete0 = 0) AND (SYS.Client0 = 1)and SYS.Netbios_Name0 not like '%-%'

2 个答案:

答案 0 :(得分:2)

使用LEFT功能

SELECT S.Netbios_Name0 AS ComputerName, LEFT(S.Netbios_Name0, 4) AS NewColumn
FROM dbo.v_R_System AS S
INNER JOIN dbo.v_GS_PROCESSOR AS P ON S.ResourceID = P.ResourceID 
INNER JOIN dbo.v_GS_COMPUTER_SYSTEM AS C ON S.ResourceID = C.ResourceID
WHERE S.Obsolete0 = 0
AND S.Client0 = 1
AND S.Netbios_Name0 NOT LIKE '%-%'

答案 1 :(得分:2)

使用派生表:

select dt.Computer.Name, LEFT(ComputerName,4) as NewColumn
(
SELECT   SYS.Netbios_Name0 as ComputerName   
FROM         dbo.v_R_System AS SYS INNER JOIN
                  dbo.v_GS_PROCESSOR AS Processor ON SYS.ResourceID = Processor.ResourceID INNER JOIN
                  dbo.v_GS_COMPUTER_SYSTEM ON SYS.ResourceID = dbo.v_GS_COMPUTER_SYSTEM.ResourceID
WHERE     (SYS.Obsolete0 = 0) AND (SYS.Client0 = 1)and SYS.Netbios_Name0 not like '%-%'
) dt

修改LEFT,而不是SUBSTR。谢谢马特!