如何以特定格式显示sql查询

时间:2015-09-24 11:44:52

标签: sql sql-server

我是SQL新手。我试图让我的查询以下面的格式显示:

FacultyName          Book     Book chapter   Journal Article     Conference
CLM                   5            11              5                 1
Health Sciences       1            0               0                 0
Humanities            1            0               0                 0
Science               0            0               0                 3

目前,这就是它的显示方式:

FacultyName              Type            CountOfSubmissionID
CLM                      Book                     5
CLM                      Book chapter             11
CLM                      Conference               1
CLM                      Journal article          5
Health Sciences          Book                     1
Humanities               Book                     1
Science                  Conference               3

这个问题让我想到了这个:

SELECT Faculty.FacultyName,
       Submission.Type,
       Count(Submission.SubmissionID) AS CountOfSubmissionID
FROM Submission
  INNER JOIN ((Faculty INNER JOIN School ON Faculty.FacultyID = School.[Faculty ID])
    INNER JOIN (Researcher INNER JOIN ResearcherSubmission
                  ON Researcher.ResearcherID = ResearcherSubmission.ResearcherID)
        ON School.SchoolID = Researcher.SchoolID)
      ON Submission.SubmissionID = ResearcherSubmission.SubmissionID
GROUP BY Faculty.FacultyName, Submission.Type

以下是我的表格:

Table Structure

请告知我如何以我绘制的第一个表的格式显示查询。

1 个答案:

答案 0 :(得分:4)

您可以使用CASE。在你的代码中试试这句话:

 SELECT Faculty.FacultyName, 
        SUM( CASE WHEN Submission.Type='Book' THEN 1 ELSE 0 END) Book,
        SUM( CASE WHEN Submission.Type='Book Chapter' THEN 1 ELSE 0 END) BookChapter,
        SUM( CASE WHEN Submission.Type='Conference' THEN 1 ELSE 0 END) Conference
 FROM Submission INNER JOIN ((Faculty INNER JOIN School ON Faculty.FacultyID = School.[Faculty ID]) INNER JOIN (Researcher INNER JOIN ResearcherSubmission ON Researcher.ResearcherID = ResearcherSubmission.ResearcherID) ON School.SchoolID = Researcher.SchoolID) ON Submission.SubmissionID = ResearcherSubmission.SubmissionID
 GROUP BY Faculty.FacultyName, Submission.Type;

祝你好运!