2010-02-01 100 views
1
 

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 [email protected] 1 7 0  208 
290 Williams Craig [email protected] 1 9 3  210 
290 Williams Craig [email protected] 1 7 5 1/29/2010 3:06:23 PM 204 
290 Williams Craig [email protected] 1 8 6 2/1/2010 9:26:40 AM 209 
 

我們正在努力恢復與最大cyclenumber該用戶ID匹配的唯一不重複的用戶ID行。現在,查詢對於不同的循環號返回相同的用戶標識多次。我們並不確定如何繼續進行正確的查詢。任何幫助,將不勝感激。幫助我們解決這個問題的SQL語句

+0

'(CycleCurrentStep)'之前是否有MAX丟失? – Greg

+0

基本上,您需要做的是運行一個查詢,獲取每個用戶的最大值(CycleNumber),然後加入到其中以獲取有關該特定User/CycleNumber組合的其餘數據 – Leslie

回答

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部分。

2

從您的group by子句中刪除CycleCurrentStep。

1

這可能是因爲你在c.CycleCurrentStep上分組。這是一個來自Cycle的未聚合列 - 如果Cycle中的所有行出現CycleCurrentStep的多個不同值(對應於User的一行),那麼您將在結果中得到與該用戶一樣多的行對於CycleCurrentStep

值您可以從GROUP BY列表中刪除CycleCurrentStep列,但隨後你將不得不也從SELECT列表中刪除它 - 那是因爲你不能在同一時間聚集所有相應Cycle行作爲一個組,然後選擇一個沒有絲毫價值的數據並報告。因此,如果您從GROUP BY中刪除CycleCurrentStep,則必須將其從SELECT列表中刪除,或者對其應用有意義的合計功能,就像您對應用MAX()函數的其他列中的Cycle一樣。

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