我有两个布尔列的以下示例数据:
ID Male Female
1 1 0
2 0 1
3 0 1
4 1 0
5 0 1
我想将两列合并为一个只包含'M'和'F'的列。另外,我最好在定义列时在SELECT语句中执行此操作。
结果应该是:
ID Gender
1 M
2 F
3 F
4 M
5 F
我知道我可以通过单独的更新语句实现这一点,例如:
UPDATE table_1
SET Gender='M'
FROM table_2 t2
WHERE t2.Male=1
和
UPDATE table_1
SET Gender='F'
FROM table_2 t2
WHERE t2.Female=1
但我真的希望在宣布性别列时能够达到相同的效果吗?
有人知道这是否可行?
提前致谢!
答案 0 :(得分:2)
您可以使用CASE
表达式。
<强>查询强>
UPDATE t1
SET t1.Gender = (
CASE WHEN t2.Male = 1 AND t2.Female = 0 THEN 'M'
WHEN t2.Male = 0 AND t2.Female = 1 THEN 'F'
ELSE NULL END
)
FROM Table_1 t1
JOIN Table_2 t2
ON t1.ID = t2.ID;
答案 1 :(得分:1)
<System.Web.Services.WebMethod()>
Public Shared Sub UploadFile()
Try
Dim file As HttpPostedFile = HttpContext.Current.Request.Files("file")
Dim fname As String = Path.GetFileName(file.FileName)
Dim ftype As String = file.ContentType
Dim sDatasource As String = String.Empty
Dim inputArray(flen) As Byte
Dim myStream As System.IO.Stream
If (Current.Request.Files.Count > 1) Then
file = HttpContext.Current.Request.Files("file")
fname = Path.GetFileName(file.FileName)
ftype = file.ContentType
flen = file.ContentLength
myStream = file.InputStream
'read the file into the byte array
myStream.Read(inputArray, 0, flen)
End If
If Not HttpContext.Current.Session.Contents("datasource") Is Nothing Then sDatasource = HttpContext.Current.Session.Contents("datasource").ToString()
Using con As New SqlConnection(sDatasource)
Using cmd As New SqlCommand
cmd.CommandText = "test_insertDoc"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("referenceno", 0)
cmd.Parameters.AddWithValue("doctype", ftype)
cmd.Parameters.AddWithValue("line", 0)
cmd.Parameters.Add("uploadedfile", SqlDbType.VarBinary, -1).Value = inputArray
cmd.Parameters.AddWithValue("customer", 0)
cmd.Parameters.AddWithValue("warehouse", 0)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
cmd.Dispose()
End Using
End Using
Catch ex As Exception
End Try
End Sub
当然我试图保持开放态度并猜测你允许UPDATE table_1
SET Gender= CASE WHEN Male = 1 THEN 'M'
WHEN Female = 1 THEN 'F'
ELSE 'Other' // optional
END;
否则,您可以使用 IIF
Male = 0 and Female = 0
答案 2 :(得分:1)
以下是使用SELECT语句的方法:
SELECT ID,
CASE WHEN Male = 1 THEN 'M'
ELSE 'F' END AS gender
FROM My_Table
答案 3 :(得分:0)
select if(Male = 1, 'M', 'F') as gender
怎么样?