使用sql查找按日期字段的第一个键,输出也有其他字段

时间:2017-05-24 20:21:24

标签: sql greatest-n-per-group vertica

我想根据最早的日期查询每个名字的第一个匹配项。输出应该有完整的行。请帮我在sql中编写查询。

输入:

null

输出:

  Name |    ID |    payment_date |  Pack
 ------+-------+-----------------+-------
    A  |    11 |    31-Jan       |  P
    C  |    13 |    31-Jan       |  Q
    B  |    2  |    31-Jan       |  R
    C  |    3  |    28-Jan       |  P
    D  |    23 |    29-Jan       |  Q
    B  |    11 |    30-Jan       |  R
    A  |    17 |    25-Jan       |  P
    C  |    13 |    26-Jan       |  Q
    D  |    17 |    2-Feb        |  R
    B  |    23 |    3-Feb        |  P
    A  |    45 |    4-Feb        |  Q
    B  |    3  |    5-Feb        |  R

3 个答案:

答案 0 :(得分:0)

如果您的payment_date是日期数据类型,则可以使用not exists(),如下所示:

select *
from t
where not exists (
  select 1
  from t i
  where i.Name = t.Name
    and i.payment_date < t.payment_date
    )

rextester demo(sql server):http://rextester.com/OKB46268

返回

+------+----+-------------+------+
| Name | Id | PaymentDate | Pack |
+------+----+-------------+------+
| A    | 17 | 2017-01-25  | P    |
| B    | 11 | 2017-01-30  | R    |
| C    | 13 | 2017-01-26  | Q    |
| D    | 23 | 2017-01-29  | Q    |
+------+----+-------------+------+

答案 1 :(得分:0)

您可以使用min函数,同时假设new_df = old_tax_df.query("var_1 == var_2 == 1") 是日期类型:

payment_date

关于此方法的垮台是将所有字段放在组中。

答案 2 :(得分:0)

您还可以使用Vertica增强的LIMIT子句:

WITH
-- input, don't use in real query
input(Name,ID,payment_date,Pack) AS (
          SELECT 'A',11,DATE '31-Jan-2017','P'
UNION ALL SELECT 'C',13,DATE '31-Jan-2017','Q'
UNION ALL SELECT 'B',2, DATE '31-Jan-2017','R'
UNION ALL SELECT 'C',3, DATE '28-Jan-2017','P'
UNION ALL SELECT 'D',23,DATE '29-Jan-2017','Q'
UNION ALL SELECT 'B',11,DATE '30-Jan-2017','R'
UNION ALL SELECT 'A',17,DATE '25-Jan-2017','P'
UNION ALL SELECT 'C',13,DATE '26-Jan-2017','Q'
UNION ALL SELECT 'D',17,DATE  '2-Feb-2017','R'
UNION ALL SELECT 'B',23,DATE  '3-Feb-2017','P'
UNION ALL SELECT 'A',45,DATE  '4-Feb-2017','Q'
UNION ALL SELECT 'B',3, DATE  '5-Feb-2017','R'
)
-- end of input , start real query here:
SELECT * FROM input
LIMIT 1 OVER(PARTITION BY Name ORDER BY payment_date)
;

快乐的比赛...... Marco the Sane