从sql中的三个表中选择数据

时间:2015-06-01 06:31:55

标签: sql sql-server join group-by

我有三张表喜欢

学生:Sid,SName,SEmail

费用_类型:Fid,FName,FPrice

StudentFees :Sid(来自学生的 FK ),Fid(来自Fees_Type 的 FK),FDate

每个表的数据:

Student : 
SID |SName | SEmail      
1   | ABC  | ABC@www.com
2   | XYZ  | xyz@www.com  

Fees_Type: 
    Fid | FName   | FPrice
    1   | Chess   | 100
    2   | Cricket | 200

StudentFees: 
        Sid | Fid| FDate
        1   | 1  | 5/2
        1   | 2  | 6/2
        2   | 1  | 7/2
        2   | 2  | 8/2
        1   | 1  | 6/2

现在我想获取数据

SID|SName|SEmail      | Total_Chess_Played|Total_Cricket_Played | ToTal_Fees
1  | ABC |ABC@www.com |      2            |         1           |  400
2  | XYZ |xyz@www.com |      1            |         1           |  300

我已尝试过以下查询,但无法获得分组依据或完美结果

SELECT s.sId, SEmail, SName, FName ,FPrice
  FROM Student s
   INNER JOIN StudentFees sf ON s.sId = sf.EId
   INNER JOIN Fees_Type f ON f.fId = sf.fId
 WHERE MONTH(pr.TDDate) = MONTH(dateadd(dd, 1, GetDate())) AND
YEAR(pr.TDDate) = YEAR(dateadd(dd, -1, GetDate())) 

我是SQL新手。所以请帮助我。

谢谢。

2 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT
    Student.SID,
    Student.SName,
    Student.SEmail,
    SUM(CASE WHEN Fees_Type.FName='Chess' THEN 1 ELSE 0 END) AS Total_Chess_Played,
    SUM(CASE WHEN Fees_Type.FName='Cricket' THEN 1 ELSE 0 END) AS Total_Cricket_Played,
    SUM(Fees_Type.FPrice) AS ToTal_Fees
FROM
    Student 
    JOIN StudentFees ON Student.sId = StudentFees.EId
    JOIN Fees_Type ON Fees_Type.fId = StudentFees.fId
WHERE 
    MONTH(StudentFees.TDDate) = MONTH(dateadd(dd, 1, GetDate())) AND
    YEAR(StudentFees.TDDate) = YEAR(dateadd(dd, -1, GetDate())) 
GROUP BY
    Student.SID,
    Student.SName,
    Student.SEmail

答案 1 :(得分:1)

试试这个

SELECT
    s.SID,
    s.SName,
    s.SEmail,
    SUM(CASE WHEN ft.FName='Chess' THEN 1 ELSE 0 END) AS Total_Chess_Played,
    SUM(CASE WHEN ft.FName='Cricket' THEN 1 ELSE 0 END) AS Total_Cricket_Played,
    SUM(ft.FPrice) AS ToTal_Fees
FROM
    Student s
    JOIN StudentFees sf ON s.sId = sf.Sid
    JOIN Fees_Type ft ON ft.fId = sf.fId
GROUP BY
    s.SID,
    s.SName,
    s.SEmail