如果使用INNER JOIN指定SELECT DISTINCT,则ORDER BY项必须出现在选择列表中

时间:2014-10-31 07:43:30

标签: sql sql-server

我的查询有问题,我读了一些suggestions,但没有运气。

我有3个表,阶段,阶段和时间表。

安排专栏:

ID,StageId,PhaseId,Duration,ScheduleType

舞台专栏:

StageId,StageName

阶段列:

PhaseId,PhaseName

这就是我想要得到的东西:

DECLARE @actual_startdate date = '2014-01-10'
SELECT 
    DISTINCT (C.PhaseName), 
    A.Duration, 
    @actual_startdate StartDate, 
    DATEADD(dd, A.Duration, @actual_startdate) EndDate 
FROM Schedule A
INNER JOIN Stages B
ON A.StageId = B.StageId
INNER JOIN Phase C
ON A.PhaseId = C.PhaseId
WHERE A.Schedule = '2' and B.Stage = '0.25'
ORDERBY B.StageId DESC;

我收到了这个错误:

如果指定了SELECT DISTINCT,

ORDER BY项必须出现在选择列表中。

我尝试了其他建议,我的研究使用 GROUP BY 子句代替DISTINCT,但仍然没有运气。

我试过了:

DECLARE @actual_startdate date = '2014-01-10'
SELECT 
    C.PhaseName, 
    A.Duration, 
    @actual_startdate StartDate, 
    DATEADD(dd, A.Duration, @actual_startdate) EndDate 
FROM Schedule A
INNER JOIN Stages B
ON A.StageId = B.StageId
INNER JOIN Phase C
ON A.PhaseId = C.PhaseId
WHERE A.Schedule = '2' and B.Stage = '0.25'
GROUP BY C.PhaseName
order BY B.StageId DESC;

又出现了新的错误:

专栏' Schedule.Duration'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

希望有人可以帮助我。谢谢! :)

1 个答案:

答案 0 :(得分:1)

您需要在Group By Clause中添加A.Duration

DECLARE @actual_startdate date = '2014-01-10'
SELECT 
    C.PhaseName, 
    A.Duration, 
    @actual_startdate StartDate, 
    DATEADD(dd, A.Duration, @actual_startdate) EndDate 
FROM Schedule A
INNER JOIN Stages B
ON A.StageId = B.StageId
INNER JOIN Phase C
ON A.PhaseId = C.PhaseId
WHERE A.Schedule = '2' and B.Stage = '0.25'
GROUP BY C.PhaseName,A.Duration,B.StageId 
order BY B.StageId DESC;