时间:2017-03-07 15:27:04

标签: sql teradata

我需要使用Teradata SQL的帮助,希望你能提供帮助。 我有一张看起来像这样的表:

email | article number | discount | price
customer01@test.de | 123 | 15 | 999
customer01@test.de | 456 | 30 | 1999
customer01@test.de | 789 | 30 | 999

从这张表中我只希望来自折扣最高的客户的行和(如果有多行具有相同折扣)最低价格。

所以在上面的例子中,我只想要第3行。如何为此编写SQL查询?

3 个答案:

答案 0 :(得分:2)

最灵活的方式是使用ROW_NUMBER:

select * from myTable
QUALIFY 
   ROW_NUMBER()
   OVER (PARTITION BY email -- for each customer, otherwise remove it
         ORDER BY discount DESC, price ASC) = 1

答案 1 :(得分:1)

最简单的方法是通过折扣(降序)和价格(升序)排序的简单选择语句。

SELECT * FROM customers
ORDER BY discount DESC, price ASC
LIMIT 1

答案 2 :(得分:0)

仅当没有其他具有较高折扣的行或具有相同折扣且价格较低的其他行时,才使用NOT EXISTS返回行。

select *
from tablename t1
where not exists (select 1 from tablename t2
                  where t2.discount > t1.discount
                     or (t2.discount = t1.discount and t2.price < t1.price))