我的表结构:
consumer_id, signup_date, plan_id, subscription_date
它有相同consumer_id的多个subscription_dates。
我在结果中需要的是具有first(min)subscription_date的所有字段,其中plan_id不是特定值。
没有我试过的where子句:
select consumer_id,
signup_date,
plan_id,
min(subscription_date)
from myTable
Group by consumer_id
我收到错误声明
列' signup_date',' plan_id'在选择列表中无效,因为 它不包含在聚合函数或GROUP BY中 子句。
但我不希望将结果分组为' signup_date'或者' plan_id'。
' signup_date'行中的值是多少?和' plan_id'在我获得每个consumer_id的最早的subscription_date之后,这就是我想要的值。如何在SQL中编写此条件?
答案 0 :(得分:3)
你可以试试这个:
select consumer_id, signup_date, plan_id
, min(subscription_date) over (partition by consumer_id)
from myTable
如果需要,您可以使用您的位置删除不需要的行。
答案 1 :(得分:0)
如果没有其他行具有相同的consumer_id但存在更早的日期,请使用NOT EXISTS
返回一行:
select consumer_id,
signup_date,
plan_id,
subscription_date
from myTable t1
where not exists (select 1 from myTable t2
where t2.consumer_id = t1.consumer_id
and t2.subscription_date < t1.subscription_date)
如果有两个来自相同的,最早的日期,则返回两行。
答案 2 :(得分:-1)
尝试此查询
select a.consumer_id,
a.signup_date,
a.plan_id,
b.subcription_date
from myTable as a
join(
select consumer_id,
min(subscription_date) as subcription_date
from myTable
Group by consumer_id ) b on a.subcription_date=b.subcription_date and a.consumer_id=b.consumer_id
答案 3 :(得分:-1)
select consumer_id,
signup_date,
plan_id,
min(subscription_date)
from myTable
Group by consumer_id, signup_date, plan_id