我有两列的表,但我想得到四列的结果

时间:2014-04-10 15:10:29

标签: sql sql-server-2008

这是我的代码

CREATE TABLE Students
(
id int PRIMARY KEY IDENTITY,
name char(25)
)

INSERT INTO Students(name) VALUES('Farhat')
INSERT INTO Students(name) VALUES('shoaib')
INSERT INTO Students(name) VALUES('rameez')
INSERT INTO Students(name) VALUES('rafay')
INSERT INTO Students(name) VALUES('ata')
INSERT INTO Students(name) VALUES('fakhar')


SELECT
CASE WHEN s.id%2=1 THEN s.id 
END AS Student_id,
CASE WHEN s.id%2=1 THEN  s.NAME END AS student_name,
CASE WHEN s.id%2=0 THEN s.id 
END AS Student_Id,
CASE WHEN s.id%2=0 THEN s.NAME END AS Student_Name
FROM students s

和结果是

1       Farhat     NULL     NULL  
NULL    NULL       2        shoaib  
3       rameez     NULL     NULL  
NULL    NULL       4        rafay                      
5       ata        NULL     NULL  
NULL    NULL       6        fakhar  

但我希望得到的结果

1 Farhat     2  shoaib  
3 rameez     4  rafay  
5 ata        6  rakhar  

表示我在此表中有两列,我希望得到四列

的结果

2 个答案:

答案 0 :(得分:0)

好吧,只是因为我觉得我尝试了一些会很有趣,但我建议不要使用它。

SELECT s1.id, s1.name, s2.id, s2.name
FROM students s1, students s2
WHERE (s2.id - s1.id = 1 
AND s1.id %2 == 1);

有一些警告,1如果有一个奇数的学生,最后一个学生将不会被打印。 (它根本不处理这种情况,我想不出任何解决方法。)

但在我看来,你应该做的事情如下:

 data = DB.query("SELECT s.id, s.name FROM Students s");
 for (i=0; i < length(data); i++)
     for (j=0; j<2; j++)
         print data[i+j].id, data[i+j].name;
     endfor
     print "\n";
 endfor

请注意,这只是伪代码,因此您必须对其进行调整。 (同样i+j容易溢出数组)

答案 1 :(得分:0)

SELECT std1.id AS Student_Id, 
        std1.NAME AS Student_Name, 
        std2.id AS Student_Id, 
        std2.NAME AS Student_Name
FROM students std1, students std2
WHERE (std2.id - std1.id = 1
       AND std1.id %2 = 1);