SQL Case MAX WHEN类

时间:2018-08-28 17:11:28

标签: sql max case sql-like

我想为我所拥有的特定异常案例创建一个案例声明或高于等级的声明。

我不确定如何使用CASE(伪代码)编写case语句

WHEN MAX Total_Revenue COMPANY like 'ABC%'
else COMPANY

我已经尝试过排名,但是没有用:

,RANK() OVER(COMPANY LIKE 'DEF%' ORDER BY  Total_Revenue DESC) AS grp

当前表:

Company    Total_Revenue
ABC        10
DEF1       25 --This row will NOT be selected as its less than
DEF2       35 -- this row will be kept    
GHI3       65
JKL9       100  

输出表:

Company    Total_Revenue
ABC        10
DEF2       35     --kept 
GHI3       65
JKL9       100  

4 个答案:

答案 0 :(得分:2)

有很多方法可以使您看起来像在做之后:

使用子查询查找每个组合的最大收入:

SELECT Company, Total_Revenue
FROM myTable
  INNER JOIN 
    (
      SELECT Left(Company, 3) as leftcomp, 
        max(Total_Revenue) as maxTotalRevenue
      FROM mytable
      GROUP BY Left(Company, 3) 
    ) mt
    ON Left(myTable.Company, 3) = mt.leftcomp
    AND myTable.Total_Revenue = mt.maxTotalRevenue;

稍后通过Where过滤的窗口函数:

SELECT *
FROM
  (
    SELECT Company, 
      Total_Revenue,
      MAX(Total_Revenue) OVER (PARTITION BY Left(Company, 3)) as maxTotalRevenue
    FROM myTable
  ) mt
 WHERE Total_Revenue = maxTotalRevenue;

WHERE子句中的相关子查询:

 SELECT *
 FROM myTable mt1
 Where Total_Revenue =
   (
     SELECT max(total_revenue)
     FROM myTable
     WHERE Left(myTable.Company, 3) = Left(mt1.Company, 3)
   );

SQLFiddle here

答案 1 :(得分:0)

您似乎想要row_number()函数:

SELECT t.*
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY LEFT(Company, 3) ORDER BY Total_Revenue DESC) AS Seq
      FROM table t
     ) t
WHERE Seq =  1;

答案 2 :(得分:0)

使用聚合函数max()和子查询

    select * from Yourtable t1
 where t1.Total_Revenue in (

  select max(T.Total_Revenue ) as Total_Revenue from
   ( 
   select case when Company like'%DEF%' then 'DEF'
   else Company end as Company , 
    Total_Revenue from Yourtable
   ) as T
    group by T.Company
   )

http://sqlfiddle.com/#!18/e896c/5

    Company  Total_Revenue
     ABC      10
     DEF2     35
     GHI3     65
     JKL9     100

答案 3 :(得分:0)

这就是你想要的吗?

select * from t
where
Company not in (
    select Company from t where Company like '%DEF%' order by Company desc offset 1 
)