我必须编写一个在2行之间搜索的查询,但只匹配两行中的值。我搜索的数据是一个包含名字和姓氏的表是单独的行。不要告诉我,我应该把它们存放在同一行。我不能,这就是需要说的。我需要做的是有一个组合记录的查询,以便我可以在不同的列中搜索它们。
数据格式如下:
StudentValues
ID
StudentID
FieldID
Response
fieldid为1给出了响应列中的第一个名称,fieldid为2给出了响应列中的姓氏,StudentID将用于对记录进行分组。
我已经能够构建以下SQL但where子句现在失败
SELECT StudentId, MIN(CASE WHEN FieldId = 1 THEN Response ELSE NULL END) AS fname, MIN(CASE WHEN FieldId = 2 THEN Response ELSE NULL END) AS lname
FROM sms_studentvalues
WHERE fname = 'Some Value'
AND lname = 'Some Value'
GROUP BY studentid
答案 0 :(得分:2)
在评论后更新
SELECT *
FROM (
SELECT StudentId,
MIN(CASE WHEN FieldId = 1 THEN Response ELSE NULL END) AS Name,
MIN(CASE WHEN FieldId = 2 THEN Response ELSE NULL END) AS LastName
FROM YourTable
GROUP BY StudentId) AS StudentsNames
WHERE Name = 'Some Value' AND LastName = 'Some Value'
答案 1 :(得分:1)
你有没有想过在FieldID上使用PIVOT?这将允许您在同一查询中同时提取名字和姓氏(FieldID = 1,FieldID = 2)。
答案 2 :(得分:0)
SELECT *
FROM StudentValues s1 JOIN StudentValues s2 ON
s1.StudentID = s2.StudentID
WHERE
s1.FieldID = 1 AND s1.Response = 'Larry' AND
s2.FieldID = 2 AND s2.Response = 'Ellison'
答案 3 :(得分:0)
SELECT a.ID, a.StudentID, a.Response, b.Response
FROM StudentValues a
INNER JOIN StudentValues B ON a.ID=b.ID and b.FieldID=2
WHERE a.FieldID=1
答案 4 :(得分:0)
联接可以这样做:
SELECT
svf.Response AS FirstName,
svl.Response AS LastName
FROM StudentValues svf
INNER JOIN StudentValues svl ON svf.StudentID = svl.StudentID
AND svl.FieldID = 2
WHERE svf.FieldID = 1