10

我希望将一列转换为字符串,其中该列是一个选择语句,然后与另一列连接。这就是我在使用 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。

4

6 回答 6

11

对于 MSSQL-2005 中的连接数字,您应该使用 CAST

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

loginsFailed 和 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))
于 2013-03-08T17:00:55.730 回答
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))

来源

于 2013-03-08T16:56:35.780 回答
2

您可以使用CASTor执行以下操作CONVERT

CONVERT(VARCHAR(20), YourIntColumn)

或者

CAST(YourIntColumn AS VARCHAR(20))
于 2013-03-08T16:58:42.820 回答
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
于 2013-03-08T17:00:10.607 回答
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
于 2013-03-08T17:05:56.527 回答
0

我认为这会成功

Select column1 + '/' + column2 from table1
于 2013-03-08T17:06:11.593 回答