帮助我们修复这个sql语句

时间:2010-02-01 22:18:48

标签: sql sql-server


SELECT DISTINCT u.UserID, UserLastName, UserFirstName, UserName, Notified, 
MAX (CycleNumber) as CycleNumber, (CycleCurrentStep) as CycleCurrentStep, 
MAX (CycleDateReported) as CycleDateReported, 
max (cycleid)
FROM [User] u 
left join Cycle c on (u.UserID = c.UserID) 
join UserDivSection us on (u.UserID = us.UserID 
and us.DivSectionID=26) 
group by u.UserID, UserLastName, UserFirstName, UserName, Notified, c.CycleCurrentStep


UserID  UserLastName    UserFirstName   UserName    Notified    CycleNumber CycleCurrentStep    CycleDateReported   
290 Williams    Craig   craasdf@gmail.com   1   7   0       208
290 Williams    Craig   craasdf@gmail.com   1   9   3       210
290 Williams    Craig   craasdf@gmail.com   1   7   5   1/29/2010 3:06:23 PM    204
290 Williams    Craig   craasdf@gmail.com   1   8   6   2/1/2010 9:26:40 AM 209

我们尝试返回具有与该用户标识的最大循环数匹配的唯一非重复用户标识的行。现在,对于各种循环数,查询将多次返回相同的用户ID。我们不确定如何继续正确的查询。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:2)

从group by子句中删除CycleCurrentStep。

答案 1 :(得分:1)

这可能是因为你在c.CycleCurrentStep上分组了。这是来自Cycle的未聚合列 - 如果CycleCurrentStepCycle的所有行中都有多个不同的User值,对应CycleCurrentStep中的一行,那么您将获得结果中该用户的许多行,因为CycleCurrentStep

有不同的值

您可以从GROUP BY列表中删除SELECT列,但之后您还必须从Cycle列表中删除它 - 因为您无法同时汇总所有列相应的CycleCurrentStep行作为一个组,然后选择一个未标记的值并报告它。因此,如果您从GROUP BY中删除SELECT,则必须将其从Cycle列表中删除,或者对其应用有意义的aggreagate函数,就像使用MAX()中的其他列一样。 {1}}您应用了{{1}}功能。

答案 2 :(得分:1)

SELECT
    u.UserID, 
    UserLastName, 
    UserFirstName, 
    UserName, 
    Notified, 
    c.CycleNumber, 
    c.CycleCurrentStep, 
    c.CycleDateReported, 
    c.cycleid
FROM
    [User] u 
    INNER JOIN 

    (SELECT 
        u.UserID
        Max(CycleNumber) CycleNumber,
    FROM 
        [User] u 
        left join Cycle c on (u.UserID = c.UserID) 
    GROUP BY
        u.UserID) MaxCycle
    ON u.UserID = MaxCycle.UserId
    INNER JOIN Cycle c
    ON MaxCycle.Cycleumber = c.CycleNumber

答案 3 :(得分:0)

您可以在where子句中使用子查询来执行此操作。类似的东西:

SELECT u.UserID, UserLastName, UserFirstName, UserName, Notified, 
CycleNumber, CycleCurrentStep, CycleDateReported, cycleid
FROM [User] u 
left join Cycle c on (u.UserID = c.UserID) 
join UserDivSection us on (u.UserID = us.UserID and us.DivSectionID=26) 
where cyclenumber = ( select max(cyclenumber) from cycle where cycle.userid = u.userid)

我不确定UserDivSection部分。