按列值选择项目

时间:2015-01-12 21:02:16

标签: sql sqlite select

我在sql中有一个用于存储结果的表

Result
---------------
ID | DateCreated
1  | 2014-10-10

上述结果下的项目

ResultItems
---------------
ResultID | StudentID | SubjID    | Test1 | Test2 | Exam
1        | 1         | 1         | 7     | 7     | 30
1        | 2         | 1         | 8     | 8     | 35
1        | 1         | 2         | 5     | 5     | 45
1        | 2         | 2         | 6     | 6     | 40

我需要从这些表格中进行选择,以便每个主题都在自己的专栏中,每个主题的得分总和在其下面

结果项目

Result Output
---------------
StudentID| SubjID-1  | SubjID-2
1        | 44        | 55      
2        | 51        | 52      

我确实尝试过安静一些查询,例如下面这个,但没有给出我需要的结果

SELECT r.*,
       ri.StudentID,
       ri.Test1,
       ri.Test2,
       ri.Exam,
       ( ri.Test1+ ri.Test2 + ri.Exam )  Total
  FROM Result r
       LEFT JOIN ResultItems ri
              ON ri.ResultID = r.id
 WHERE ri.Test1 <> '-' 
       AND
       ri.Test2 <> '-' 
       AND
       ri.exam <> '-';

您能否提供查询帮助

修改

我读到了关于Pivot并看到了这个问题SQL - columns for different categories,在这种情况下,主题的名称/ ID必须事先知道,这对我的情况不起作用

1 个答案:

答案 0 :(得分:1)

SQL Server解决方案

您需要的只是Pivot

CREATE TABLE #ResultItems
(
    ResultID INT,
    StudentID INT,
    SubjID INT,
    Test1 INT,
    Test2 INT,
    Exam INT
)


INSERT INTO #ResultItems (ResultID, StudentID, SubjID, Test1, Test2, Exam)
VALUES(1, 1 , 1 , 7, 7, 30),
(1, 2 , 1 , 8, 8, 35),
(1, 1 , 2 , 5, 5, 45),
(1, 2 , 2 , 6, 6, 40)

SELECT StudentId, [1], [2]
FROM (
    SELECT StudentId, SubjID, Test1 + Test2 + Exam AS TmpSum
    FROM #ResultItems
) AS DT
PIVOT(SUM(TmpSum) FOR SubjID IN ([1], [2])) AS PT

DROP TABLE #ResultItems 

SQLite解决方案

使用CASE

SELECT StudentId, SUM(Subj1) AS Subj1, SUM(Subj2) As Subj2
FROM (
SELECT t1.StudentId, CASE WHEN SubjID = 1 THEN Test1 + Test2 + Exam ELSE 0 END AS Subj1,
        CASE WHEN SubjID = 2 THEN Test1 + Test2 + Exam ELSE 0 END  AS Subj2
    FROM #ResultItems AS t1
) AS T
GROUP BY T.StudentID 

或子查询:

SELECT t1.StudentId, (SELECT Test1 + Test2 + Exam FROM #ResultItems WHERE StudentID = t1.StudentID AND SubjID = 1) AS Subj1,
        (SELECT Test1 + Test2 + Exam FROM #ResultItems WHERE StudentID = t1.StudentID AND SubjID = 2) AS Subj2
    FROM #ResultItems AS t1
GROUP BY t1.StudentID