用于转换Reports报表数据的SQL Query

时间:2015-02-14 11:36:29

标签: sql-server

我正在考虑将以下数据转换成可以在报告中投影的数据,但是在Vain中。任何帮助将不胜感激。

Student - Table
----------------
StudentID | CertID
------------------
1         | 10
2         | 20

Certification Table
-------------------
CertId | CertName
-------------------
10       Certification1
20       Certification2
30       Certification3    

Capablity Table
---------------
CapId | Capablity
-------------------
1       Capability1
2       Capability2
3       Capability3
4       Capability4
5       Capability5
6       Capability6

StudentCertification
--------------------
StudentID | CertId | CapId | TotalTasks | CompletedTasks
--------------------------------------------------------------
1           10           1           50           25
1           20           2           20            5
2           10           4           30           12

我正在寻找一个看起来像这样的最终数据

StudentId | CertId | CapId| TasksCompleted
---------------------------------
1           10           1         50%
1           10           2         NA
1           10           3         NA
1           10           4         NA
1           10           5         NA
1           10           6         NA
1           20           1         NA
1           20           2         25%
1           20           3         NA
1           20           4         NA
1           20           5         NA
1           20           6         NA
2           10           1         NA
2           10           2         NA
2           10           3         NA
2           10           4         40%
2           10           5         NA
2           10           6         NA

我已更新结果以反映学生资格认证表中的数据。

2 个答案:

答案 0 :(得分:0)

这是一个例子。没有真正理解功能表的功能,但通过交叉连接,您将获得每个学生的所有组合。

select
  s.StudentId,
  c.CertId,
  cb.CapId,
  100.0 * sc.CompletedTasks / sc.TotalTasks as TasksCompleted
from
  student s
  left outer join certification c on c.CertId = s.CertId
  cross join capability cb
  left outer join StudentCertification sc on 
      s.StudentId = sc.StudentId and c.CertId = sc.CertId and cb.CapId = sc.CapId

SQL小提琴:http://sqlfiddle.com/#!3/1145e/5

答案 1 :(得分:0)

试试这个:

SELECT SC1.StudentID ,SC1.CertId,C.CapId,
CAST((100*SC2.CompletedTasks)/SC2.TotalTasks AS VARCHAR(20)) + '%' AS TasksCompleted  
FROM StudentCertification SC1
CROSS JOIN capability  C
LEFT JOIN  StudentCertification SC2 ON SC1.StudentID=SC2.StudentID
AND SC1.CertId=SC2.CertId AND C.CapId=SC2.CapId