2014-02-27 103 views
0

假設我有如下表(實際上這是查詢的結果) enter image description here選擇金額只有第一部分

WHT我要的是拿出如下表

enter image description here

與它爲每個代碼值分配零值,除了第一個代碼值。

任何策略要做到這一點?

在此先感謝

+0

什麼是您查詢得到這個結果是什麼樣子?你到目前爲止嘗試過什麼? – NickyvV

+0

您需要金額爲0嗎?否則,你可以使用'按代碼分組' –

回答

3

這是否幫助?

declare @tab table(
     code int, 
     amount int) 

insert into @tab values 
    (1,100), 
    (1,100), 
    (1,100), 
    (2,500), 
    (2,500), 
    (3,1000); 

    select code, 
     case when rn=1 then 
      amount 
     else 0 end amount 
    from 
(select *, 
      row_number()Over(partition by code Order by amount) RN 
     from @tab)t 
1

你可以使用row_number()確定每個code的第一行。從那裏,它只是一個簡單的case表達:

SELECT code, CASE rn WHEN 1 THEN amount ELSE 0 END AS amount 
FROM (SELECT code, amount, 
       ROW_NUMBER() OVER (PARTITION BY code ORDER BY amount) AS rn 
     FROM my_table) 
0

請嘗試:

select Code, 
    case when ROW_NUMBER() over (partition by Code Order by Amount)=1 then Amount else 0 end Amount 
From YourTable 
+0

'按金額排序'是相當多餘的,因爲它們都是一樣的。 – NickyvV

1

試試這個

SELECT Code,CASE When RN > 1 Then 0 Else Amount 
FROM 
(
    SELECT *,ROW_NUMBER() OVER (Partition by Code Order by (Select Null)) RN 
    FROM Table1 
) AS T 
0

請與帳戶更新表以低於查詢:

SELECT A.code, 
     (CASE 
      WHEN A.rno = 1 THEN B.amount 
      ELSE 0 
     END) AS amount 
FROM (SELECT Row_number() 
       OVER( 
        partition BY code 
        ORDER BY code DESC) AS rno, 
       code 
     FROM account) AS A 
     LEFT OUTER JOIN (SELECT C.code, 
           Sum(C.amount) AS amount 
         FROM account C 
         GROUP BY C.code) AS B 
        ON B.code = A.code