-1

我已经尝试了很多次,但我不知道如何为每个技术人员对他们拥有的每个诊断结果(只有三种类型 1、2、3)的答案进行分组?(例如,technical ID 54 有多少个诊断结果 1。)

我尝试输入 count 函数,但它不起作用。有人可以在 SQL 中给我一些想法吗?

这是我在数据库中找到的。

TechnicianID FirstName
------------ -------------
54           Wayne

TechnicianID DiagnosisOutcomeID
------------ ------------------
54           1
54           2
54           1
54           3

The Result should be
TechnicianID FirstName    DiagnosisOutcome=1    DiagnosisOutcome=2 DiagnosisOutcome=3
------------ -------------
54           Wayne

谢谢你

4

2 回答 2

3

由于您没有提到任何 RDBMS,因此下面的查询将适用于许多 RDBMS,

SELECT  a.TechnicianID,
        a.FirstName,
        SUM(CASE WHEN b.DiagnosisOutcomeID = 1 THEN 1 ELSE 0 END) DiagnosisOutcomeID1,
        SUM(CASE WHEN b.DiagnosisOutcomeID = 2 THEN 1 ELSE 0 END) DiagnosisOutcomeID2,
        SUM(CASE WHEN b.DiagnosisOutcomeID = 3 THEN 1 ELSE 0 END) DiagnosisOutcomeID3
FROM    Table1 a
        INNER JOIN Table2 b
            ON a.TechnicianID = b.TechnicianID 
GROUP   BY a.TechnicianID, a.FirstName

如果您使用RDBMS的是支持PIVOT功能,

SELECT  TechnicianID, 
        FirstName,
        DiagnosisOutcomeID1,
        DiagnosisOutcomeID2,
        DiagnosisOutcomeID3
FROM
(
    SELECT  a.TechnicianID,
            a.FirstName,
            'DiagnosisOutcomeID' + CAST(b.DiagnosisOutcomeID AS VARCHAR(5)) AS DiagnosisOutcomeID
    FROM    Table1 a
            INNER JOIN Table2 b
                ON a.TechnicianID = b.TechnicianID 
) data
PIVOT
(
    COUNT(DiagnosisOutcomeID)
    FOR DiagnosisOutcomeID IN (DiagnosisOutcomeID1,DiagnosisOutcomeID2,DiagnosisOutcomeID3)
) pvt
ORDER BY TechnicianID
于 2013-05-12T01:57:51.677 回答
1

CASE声明是您需要的。

看看这个SQL Fiddle

SELECT T.FirstName
       ,SUM(CASE WHEN DiagnosisOutcomeID = 1 THEN 1 ELSE 0 END) AS OUTCOME1
       ,SUM(CASE WHEN DiagnosisOutcomeID = 2 THEN 1 ELSE 0 END) AS OUTCOME2
       ,SUM(CASE WHEN DiagnosisOutcomeID = 3 THEN 1 ELSE 0 END) AS OUTCOME3
FROM   Tech T
INNER JOIN
       Diagnosis D
ON     T.TechnicianID = D.TechnicianID
GROUP BY
       T.FirstName
于 2013-05-12T02:02:06.243 回答