2013-07-25 46 views
2

SAMPE表:計數和ROWNUMBER

CusID Order  Status 
3001 Hotdog Paid 
3001 Sausage Paid 
3001 Burger Unpaid 
3002 Sausage Paid 
3003 Burger Paid 
3003 Hotdog Paid 
3002 Hotdog Paid 
3001 Burger Paid 
3002 Burger Unpaid 

期望輸出繼電器

Row CusID NumOfOrdersPaid 
1  3001 3 
2  3002 2 

我嘗試這樣做:

SELECT * 
FROM (
    SELECT row_number() OVER (
     ORDER BY CusID 
    ) row 
    ,count(CASE STATUS 
     WHEN 'Paid' 
      THEN 1 
     ELSE NULL 
     END) AS NumOfOrdersPaid 
    FROM Orders 
) X 
WHERE x.r BETWEEN 1 
    AND 2 
GROUP BY CusID 

回答

2
Select * from  
(Select CusID,row_number() over (order by CusID) r, 
count(case Status when 'Paid' then 1 else null end) 
AS NumOfOrdersPaid from Table1 Group By CusID) X 
where x.r between 1 and 2; 

fiddle

+0

謝謝Praveen :) –

+0

你永遠是受歡迎的兄弟 –

0
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY CusID ASC) AS Row, CusID, NumOfOrdersPaid FROM MyTable) As List 
+0

計數在哪裏? –

+0

好吧,我明白了,我錯過了一點 – BigBadOwl