You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
select
product_id,
year as first_year,
quantity,
price
from (
select
product_id,
year,
quantity,
price,
rank() over(partition by product_id order by year) as rn
from sales
) as temp where rn =1;
select
product_id,
year as first_year,
quantity,
price
from sales where (product_id, year) in (
select product_id, min(year) from sales group by product_id
);
解析
使用 group by 按照 product_id 进行分组,查询出 product_id 和第一年 first_year
查询 sales 表,筛选出第一步中查询出来的 product_id 和 first_year
SQL:方法三
selectsales.product_id,
first_year,
quantity,
price
from (
select product_id, min(year) first_year from sales group by product_id
) as temp
left join sales ontemp.product_id=sales.product_idandtemp.first_year=sales.year;
解析
使用 group by 按照 product_id 进行分组,查询出 product_id 和第一年 first_year
将第一步作为临时表 temp 和 sales 左连,连接条件是 product_id 和 first_year = year
The text was updated successfully, but these errors were encountered:
题目
编写一个 SQL 查询,选出每个销售产品的 第一年 的
product_id
、first_year
、quantity
****和price
。sales
表中的主键是sale_id
外键是product_id
product
表中的主键是product_id
ps:如果第一年有两个价格也需要查询出来
分析
first_year
和产品idproduct_id
product
表用不到SQL:方法一
解析
rank()
,按照product_id
分组,year
升序排序,得到rn
row_number
temp
temp
筛选出rn = 1
的数据,因为rn
是升序排序的,所以rn = 1
就是第一年SQL:方法二
解析
group by
按照product_id
进行分组,查询出product_id
和第一年first_year
sales
表,筛选出第一步中查询出来的product_id
和first_year
SQL:方法三
解析
group by
按照product_id
进行分组,查询出product_id
和第一年first_year
temp
和sales
左连,连接条件是product_id
和first_year = year
The text was updated successfully, but these errors were encountered: