如何使用SQL仅显示具有来自其他列的多个值的列中的较高值

时间:2016-01-11 21:00:36

标签: sql oracle

我的数据是这样的

表:customer_error

enter image description here

我只是想将结果作为首先出现的错误ID而不是正在进行的错误ID。

enter image description here

4 个答案:

答案 0 :(得分:3)

我相信你正在寻找这个:

这是一种方式:

  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
  /

两者都使用Google Analytics(分析),这是一种非常有用的工具,我建议您阅读并学习它,因为它非常有用。

答案 1 :(得分: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;

答案 2 :(得分: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;

答案 3 :(得分:-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