我有这个查询,但由于group by子句,我无法选择所有字段。
如何重新构造查询以便检索所有信息? 我已经尝试过每个字段的GroupBy,但其中一些是文本。
SELECT p.Pato_Id, p.Description, 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
答案 0 :(得分:1)
尝试将文字字段转换为nvarchar(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
你也加入了那张桌子。