SQL:如何将两列与标点结合在一起?

时间:2022-02-22 07:51:17

I would like to combine two columns into one and separate by a '/' using SQL statement

我希望将两列合并成一个,并使用SQL语句分隔开。

Currently, I could only do this.

目前,我只能这么做。

Select A.Marks, Q.NoOfAnsBox FROM AnswerTable AS A INNER JOIN QuestionTable AS 
Q WHERE A.QuestionID = Q.QuestionID

With the output:

输出:

Marks NoOfAnsBox    
3     5    
2     5

May I know if it is possible to output it as one column as follows?

我是否可以将它输出为如下一列?

Marks    
3/5    
2/5

I tried convert the integers into string and perform concatenation but failed to obtain the desired result

我尝试将整数转换为字符串并执行连接,但没有获得所需的结果

Select (CONVERT(A.Marks, Char(50)) + '/' + Convert(Q.NoOfAnsBox,Char(50))) As     
Marks FROM AnswerTable AS A INNER JOIN QuestionTable AS Q WHERE A.QuestionID = 
Q.QuestionID


Marks    
8    
7

3 个解决方案

#1


3  

In Mysql use the CONCAT() function to concatenate strings as + acts differently here than in other RDBMS's:

在Mysql中,使用CONCAT()函数连接字符串,因为+在这里的行为与其他RDBMS不同:

Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) As Marks 
FROM AnswerTable AS A 
    INNER JOIN QuestionTable AS Q ON A.QuestionID = Q.QuestionID

Also consider changing your "WHERE" to an "ON". In your case they are synonymous, but things could get ugly if you swap your INNER join to a LEFT OUTER join and forget to monkey with the WHERE clause.

也可以考虑把“WHERE”改成“ON”。在您的例子中,它们是同义词,但是如果您将内部连接替换为左外部连接,而忘记使用WHERE子句,事情就会变得很糟糕。

#2


1  

Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) AS Marks FROM AnswerTable AS A INNER JOIN QuestionTable AS 
Q WHERE A.QuestionID = Q.QuestionID

#3


0  

use the Concat() function as follows

使用Concat()函数如下所示

 Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) AS Marks 
 FROM AnswerTable AS A INNER JOIN QuestionTable AS Q 
 WHERE A.QuestionID = Q.QuestionID

#1


3  

In Mysql use the CONCAT() function to concatenate strings as + acts differently here than in other RDBMS's:

在Mysql中,使用CONCAT()函数连接字符串,因为+在这里的行为与其他RDBMS不同:

Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) As Marks 
FROM AnswerTable AS A 
    INNER JOIN QuestionTable AS Q ON A.QuestionID = Q.QuestionID

Also consider changing your "WHERE" to an "ON". In your case they are synonymous, but things could get ugly if you swap your INNER join to a LEFT OUTER join and forget to monkey with the WHERE clause.

也可以考虑把“WHERE”改成“ON”。在您的例子中,它们是同义词,但是如果您将内部连接替换为左外部连接,而忘记使用WHERE子句,事情就会变得很糟糕。

#2


1  

Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) AS Marks FROM AnswerTable AS A INNER JOIN QuestionTable AS 
Q WHERE A.QuestionID = Q.QuestionID

#3


0  

use the Concat() function as follows

使用Concat()函数如下所示

 Select CONCAT(A.Marks, '/', Q.NoOfAnsBox) AS Marks 
 FROM AnswerTable AS A INNER JOIN QuestionTable AS Q 
 WHERE A.QuestionID = Q.QuestionID