2016-01-11 17 views
0
從其他列中的多個值的列只顯示了更高的價值

我的數據是這樣如何從具有使用SQL

表:customer_error

enter image description here

我只是想希望得到結果作爲第一個出現的錯誤ID,而不是前面的錯誤ID。

enter image description here

+1

請把你的嘗試以及 –

+0

我們應該怎麼知道發生第一?它是否在ERROR_ID順序或其他順序?除非您使用order by子句,否則Oracle不會按任何特定順序返回記錄。 – Sentinel

回答

3

我相信你正在尋找這樣的:

這裏是1路:

select distinct first_value(customer_id) over (partition by customer_id 
             order by error_id) customer_id, 
        first_value(error_id) over (partition by customer_id 
             order by error_id) error_id, 
        first_value(error_description) over (partition by customer_id 
             order by error_id) error_description 
    from customer_error 
/

和方式略有不同:

select customer_id, error_id, error_description 
    from (
     select row_number() over (partition by customer_id 
            order by error_id) rnum, 
       customer_id, error_id, error_description 
      from customer_error 
     ) 
    where rnum = 1 
/

兩者都使用Analytics(分析),一個非常有用的工具來做這種事情,我建議讀o因爲它非常有用,所以學習它。

-1

您可以使用CTE和Row_Number()函數。

with tmp1 as 
(select *, 
ROW_NUMBER() over (partition by customer_id order by error_id) as RowNum 
from YourTable 
) 

select customer_id, error_id, error_description 
from tmp1 
where RowNum = 1 

文檔上ROW_NUMBER():https://msdn.microsoft.com/en-us/library/ms186734.aspxhttps://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm

+0

問題用oracle標記,因此提供SQL Server文檔引用會引起誤解。 – Sentinel

1

該解決方案假設錯誤是由ERROR_ID訂購和使用聚合函數,而不是解析函數:

select customer_id 
     , max(error_id) KEEP (DENSE_RANK FIRST ORDER BY error_id) error_id 
     , max(error_description) KEEP (DENSE_RANK FIRST ORDER BY error_id) error_description 
    from customer_error 
    group by customer_id; 
2

如果我們假設ERROR_NUMBER最小值是首先出現的值,我們可以用普通的sql來做到這一點。我們的目標是獲得每個客戶的最小錯誤數量,然後將錯誤的相關錯誤描述粘貼到其上。

SELECT a.customer_id, a.error_id, b.error_description FROM 
    (SELECT customer_id, MIN(error_id) FROM customer_error 
     GROUP BY customer_id) a 
    LEFT JOIN customer_error b on a.error_id=b.error_id;