0

我有这个查询,但由于 group by 子句,我无法选择所有字段。

如何重新编写查询以便检索所有信息?我试过按每个字段分组,但其中一些是文本。

选择

    p.Pato_Id,
    p.描述,
    p.日期
    a.Assessment_Id,
    a.推荐,
    Question1 = MAX(CASE WHEN r.Question_Id = 0 THEN r.Answer_Id END),
    Question2 = MAX(CASE WHEN r.Question_Id = 1 THEN r.Answer_Id END)

从
    帕托斯
外用(
    选择前 1
        a.Assessment_Id
        , a. 推荐
    从
        评估
    在哪里
        a.Pato_Id = p.Pato_Id
    订购方式
        a. 日期 DESC
    ) 一个
加入
    回复
上
    a.Assessment_Id = r.Assessment_Id

通过...分组
    p.Pato_Id

4

1 回答 1

1

尝试将您的文本字段转换为 anvarchar(max)然后包括 中的所有字段group by,例如:

SELECT 
    p.Pato_Id,
    CAST(p.Description AS nvarchar(max)),
    p.Dated,
    a.Assessment_Id,
    a.Recommendation,
    Question1 = MAX(CASE WHEN r.Question_Id = 0 THEN r.Answer_Id END),
    Question2 = MAX(CASE WHEN r.Question_Id = 1 THEN r.Answer_Id END)
FROM Patos p
OUTER APPLY (
    SELECT TOP 1 
        a.Assessment_Id
        , a.Recommendation
    FROM Assessments a
    WHERE a.Pato_Id = p.Pato_Id
    ORDER BY a.Dated DESC
    ) a
JOIN Replies r
ON a.Assessment_Id = r.Assessment_Id
GROUP BY 
    p.Pato_Id,
    CAST(p.Description AS nvarchar(max)),
    p.Dated,
    a.Assessment_Id,
    a.Recommendation

哪个是文本列?假设它是 p.Description 你可以这样做:

SELECT sub.*, t.Description FROM
(SELECT 
    p.Pato_Id as Pato_Id,
    t.Description as Description,
    t.Dated as Dated,
    a.Assessment_Id as Assessment_Id,
    a.Recommendation as Recommendation,
    Question1 = MAX(CASE WHEN r.Question_Id = 0 THEN r.Answer_Id END),
    Question2 = MAX(CASE WHEN r.Question_Id = 1 THEN r.Answer_Id END)
FROM Patos p
OUTER APPLY (
    SELECT TOP 1 
        a.Assessment_Id
        , a.Recommendation
    FROM Assessments a
    WHERE a.Pato_Id = p.Pato_Id
    ORDER BY a.Dated DESC
    ) a
JOIN Replies r
ON a.Assessment_Id = r.Assessment_Id
GROUP BY 
    p.Pato_Id,
    a.Assessment_Id,
    a.Recommendation) AS sub
INNER JOIN Patos t ON
    t.Pato_Id = sub.Pato_Id

如果它也是Recommendation你的Group By变成:

GROUP BY 
    p.Pato_Id,
    a.Assessment_Id

你也加入了那张桌子。

于 2013-09-30T17:38:18.893 回答