SQL语句中的分组依据未按预期分组

时间:2014-03-26 16:09:07

标签: sql ms-access group-by

我正在寻求以下声明的帮助。我的目的是将结果按dom.OutcomeType分组,只返回结果集中的两个记录(也在下面)。有这么多分组标准的原因是因为我使用Access 2007并且它坚持在group by语句中包含每个返回值。

SQL声明

SELECT d.DiagnosticId, d.AbsenceId, dqm.QuestionNumber, dq.Question, dqm.AnswerId, dom.OutcomeType, do.Outcome, d.AcceptedId, d.Reason
FROM (((ct_adt_Diag d
    INNER JOIN ct_adt_DiagOMatch dom ON d.DiagnosticId = dom.DiagnosticId)
    INNER JOIN ct_adt_DiagOutcome do ON dom.OutcomeId = do.OutcomeId)
    INNER JOIN ct_adt_DiagQAMatch dqm ON d.DiagnosticId = dqm.DIagnosticId)
    INNER JOIN ct_adt_DiagQuestion dq ON dqm.QuestionId = dq.QuestionId
WHERE d.AbsenceId = 19
GROUP BY dom.OutcomeType, d.DiagnosticId, d.AbsenceId, dq.Question, dqm.AnswerId, dqm.QuestionNumber, do.Outcome, d.AcceptedId, d.Reason
ORDER BY d.DiagnosticId, dqm.QuestionNumber

结果 Results

由于

3 个答案:

答案 0 :(得分:0)

替换

GROUP BY dom.OutcomeType, d.DiagnosticId, d.AbsenceId, dq.Question, dqm.AnswerId, dqm.QuestionNumber, do.Outcome, d.AcceptedId, d.Reason

GROUP BY dom.OutcomeType

答案 1 :(得分:0)

您被要求将所有这些字段添加到GROUP BY子句,因为Access将您的整个查询视为聚合查询。您可以将查询拆分为两个查询,也可以在一个混乱的语句中完成,如下所示:

SELECT d.DiagnosticId, d.AbsenceId, dqm.QuestionNumber, dq.Question, dqm.AnswerId, 
dom.OutcomeType, do.Outcome, d.AcceptedId, d.Reason
FROM (((ct_adt_Diag As d
INNER JOIN (
    SELECT dom.OutcomeType
    FROM ct_adt_DiagOMatch As dom
    GROUP BY dom.OutcomeType
) ON d.DiagnosticId = dom.DiagnosticId)
INNER JOIN ct_adt_DiagOutcome do ON dom.OutcomeId = do.OutcomeId)
INNER JOIN ct_adt_DiagQAMatch dqm ON d.DiagnosticId = dqm.DIagnosticId)
INNER JOIN ct_adt_DiagQuestion dq ON dqm.QuestionId = dq.QuestionId
WHERE d.AbsenceId = 19
ORDER BY d.DiagnosticId, dqm.QuestionNumber

我希望我没有遗漏任何括号!

答案 2 :(得分:0)

你需要做这样的事情......

我不知道您的数据,但这应该让您从那个方向开始。

    WITH CTE
AS (
    SELECT d.DiagnosticId
        , MIn(d.AbsenceId) AbsenceId
        , MIN(dqm.QuestionNumber) QuestionNumber
        , MIN(dq.Question) Question
        , MIN(dqm.AnswerId) AnswerId
        , MIN(dom.OutcomeType) OutcomeType
        , MIN(do.Outcome) Outcome
        , MIn(d.AcceptedId) AcceptedId
        , MIN(d.Reason) Reason
        , ROW_NUMBER() OVER (
            PARTITION BY dom.OutcomeType ORDER BY d.DiagnosticId,, dqm.QuestionNumber
            ) rownum
    FROM (
        (
            (
                ct_adt_Diag d INNER JOIN ct_adt_DiagOMatch dom
                    ON d.DiagnosticId = dom.DiagnosticId
                ) INNER JOIN ct_adt_DiagOutcome do
                ON dom.OutcomeId = do.OutcomeId
            ) INNER JOIN ct_adt_DiagQAMatch dqm
            ON d.DiagnosticId = dqm.DIagnosticId
        )
    INNER JOIN ct_adt_DiagQuestion dq
        ON dqm.QuestionId = dq.QuestionId
    WHERE d.AbsenceId = 19
    GROUP BY dom.OutcomeType
        , d.DiagnosticId    
    )
SELECT *
FROM CTE
WHERE rownum <= 2