在SQL Select中将列转换为字符串

时间:2013-03-08 16:54:15

标签: sql sql-server-2005

我希望将列转换为字符串,其中列是选择语句,然后与另一列连接。这是我在使用CONVERT或CAST时发生混淆的地方。

示例:

 SELECT employeeID
    ,name
    ,location
    ,(SELECT COUNT(DISTINCT loginsFailed)
     FROM users
     WHERE (users.employeedID = userDetails.employeeID)
        AND (users.startdate = 01-01-2013) as LoginCountFailed
  ,(SELECT COUNT(DISTINCT logins)
   FROM users
   WHERE (users.employeedID = userDetails.employeeID)
       AND (users.startdate = 01-01-2013) as LoginCount
 FROM userDetails

现在,这个查询工作得很完美,因为它提供了正确的登录次数,并作为整数失败。但是,我想将这些整数用作字符串,因此我可以使用一列。有一个原因,为什么这需要是一列作为字符串。

我想只有4列,而不是5.我想要的登录列是loginCountFailed / LoginCount。例如:3/12。我需要它作为一个字符串,因为你不能除以0,有时候分母是0。

6 个答案:

答案 0 :(得分:11)

要在MSSQL-2005中连接数字,您应该使用CAST

CAST(loginsFailed AS VARCHAR(10)) + '/' + CAST(LoginCount AS VARCHAR(10))

登录失败,上面的loginCount实际上是您的select count distinct碎片

我希望这有效

CAST ((SELECT COUNT(DISTINCT loginsFailed) FROM users WHERE users.employeedID = userDetails.employeeID AND users.startdate = 01-01-2013) AS VARCHAR(10))
+ '/' +
CAST ((SELECT COUNT(DISTINCT logins) FROM users WHERE users.employeedID = userDetails.employeeID AND users.startdate = 01-01-2013) AS VARCHAR(10))

答案 1 :(得分:2)

DECLARE @i int
SET @i=98235

--Method 1 : Use CAST function
SELECT CAST(@i as varchar(10))

--Method 2 : Use CONVERT function
SELECT CONVERT(varchar(10),@i)

--Method 3 : Use STR function
SELECT LTRIM(STR(@i,10))

Source

答案 2 :(得分:2)

  

您可以使用CASTCONVERT

执行以下操作
CONVERT(VARCHAR(20), YourIntColumn)
  

OR

CAST(YourIntColumn AS VARCHAR(20))

答案 3 :(得分:2)

想要做的是有一个case语句来处理除零逻辑,而不是切换到数字数据的字符串。

SELECT employeeID
    ,name
    ,location
    ,(SELECT CASE WHEN COUNT(DISTINCT logins) = 0 then 0 ELSE
COUNT(DISTINCT loginsFailed) / COUNT(DISTINCT logins)
END
     FROM users
     WHERE (users.employeedID = userDetails.employeeID)
        AND (users.startdate = 01-01-2013) ) as LoginFailRatio
 FROM userDetails

答案 4 :(得分:0)

我认为你可以在这里创建一个外部查询:

SELECT u.employeeID, u.name, u.location,  
       CONVERT(varchar(10), u.LoginCountFailed) + '/' + CONVERT(varchar(10), u.LoginCount) "Ratio" 
    FROM
        (
         SELECT employeeID
            ,name
            ,location
            ,(SELECT COUNT(DISTINCT loginsFailed)
             FROM users
             WHERE (users.employeedID = userDetails.employeeID)
                AND (users.startdate = 01-01-2013) as LoginCountFailed
          ,(SELECT COUNT(DISTINCT logins)
           FROM users
           WHERE (users.employeedID = userDetails.employeeID)
               AND (users.startdate = 01-01-2013) as LoginCount
         FROM userDetails
        ) u

答案 5 :(得分:0)

我认为这会解决问题

Select column1 + '/' + column2 from table1