2013-04-24 78 views
1

我正在使用SQLServer2008。我的存儲過程的按ID組合記錄

輸出是:

-------------------------------------------------------- 
BrokerCode | MemberId | FY | SY | TY | 
-------------------------------------------------------- 
    104  | 24  | 1140 | 0.00 | 0.00 | 
-------------------------------------------------------- 
    104  | 24  | 1140 | 570 | 0.00 | 
-------------------------------------------------------- 
    104  | 30  | 500 | 0.00 | 0.00 | 
-------------------------------------------------------- 
    104  | 30  | 500 | 360 | 0.00 | 
-------------------------------------------------------- 

我想造成這樣的:

-------------------------------------------------------- 
BrokerCode | MemberId | FY | SY | TY | 
-------------------------------------------------------- 
    104  | 24  | 1140 | 570 | 0.00 | 
-------------------------------------------------------- 
    104  | 30  | 500 | 360 | 0.00 | 
-------------------------------------------------------- 

所以,我已經嘗試使用:

WITH CTE AS ( 
SELECT BrockerCode, 
    MemberId, 

    RN=ROW_NUMBER()OVER(PARTITION BY MemberId ORDER BY MemberID), 
    FY=MIN(FY)OVER(PARTITION BY MemberId), 
    SY=MIN(SY)OVER(PARTITION BY MemberId), 
    TY=MIN(TY)OVER(PARTITION BY MemberId) 

    FROM @tablePromotee) 
SELECT MemberId,BrockerCode,FY,SY,TY FROM CTE WHERE RN = 1 

但仍顯示錯誤結果...請幫助我..我錯了嗎?謝謝。

+0

不應該是'FY = MAX(FY)OVER(PARTITION BY MemberId)'而不是'MIN'? – praveen 2013-04-24 05:54:31

回答

0

嘗試這一個 -

SELECT 
     MemberId 
    , BrockerCode 
    , FY = MAX(FY) 
    , SY = MAX(SY) 
    , TY = MAX(TY) 
FROM (
    SELECT 
      BrockerCode 
     , MemberId 
     , RN = ROW_NUMBER()OVER(PARTITION BY MemberId ORDER BY MemberID) 
     , FY = MIN(FY)OVER(PARTITION BY MemberId) 
     , SY = MIN(SY)OVER(PARTITION BY MemberId) 
     , TY = MIN(TY)OVER(PARTITION BY MemberId) 
    FROM @tablePromotee 
) 
WHERE RN = 1 
GROUP BY 
     BrokerCode 
    , MemberId 

或者試試這個 -

SELECT TOP 1 
     BrockerCode 
    , MemberId 
    , FY = MAX(MIN(FY)OVER(PARTITION BY MemberId)) 
    , SY = MAX(MIN(SY)OVER(PARTITION BY MemberId)) 
    , TY = MAX(MIN(TY)OVER(PARTITION BY MemberId)) 
FROM @tablePromotee 
GROUP BY 
     BrokerCode 
    , MemberId 
ORDER BY MemberId 
0

試試這個,

SELECT BrockerCode, 
      MemberId, FY,SUM(SY),SUM(TY) FROM @tablePromotee Group By BrockerCode, 
      MemberId, FY 
+0

我不想讓總和 – Prashant16 2013-04-24 05:58:15

+0

然後去與其他答案。 – Maximus 2013-04-24 06:03:23

1

您可以簡單地使用 「GROUP BY」 在您的查詢 一樣,

SELECT BrockerCode, 
    MemberId, 
    MIN(FY) 
    MIN(SY) 
    MIN(TY) 
    FROM @tablePromotee GROUP BY BrockerCode, MemberId 

根據您的要求,您可以在sql server上使用多個集合函數。

1

Common Table Expression在這裏並不是真的需要。一個更簡單的查詢:

SELECT 
     BrokerCode, 
     MemberId, 
     MAX(FY) AS FY, 
     MAX(SY) AS SY, 
     MAX(TY) AS TY 
FROM YourTable 
GROUP BY BrokerCode, MemberId 

SQL FIDDLE DEMO

0

只需用GROUP BY不會工作,因爲你可能在獲得最終o.oo值 變化如下現有代碼的最後一行,希望你想要這個。

SELECT MemberId,BrockerCode,FY,SY,TY FROM CTE WHERE RN = 1 and SY<>0 
ROUP BY BrockerCode, MemberId