【发布时间】:2022-09-23 19:06:05
【问题描述】:
我还是 mssqlserver 的新手,我需要根据品牌名称和 customer_id 在特定时期为同一客户下订单获取第一个订单我使用 first_value() 作为前 1 的子查询但是我只得到第一个值基于品牌而不考虑客户 ID
我得到了什么
| Data | Customer_ID | Brand | first_order |
|---|---|---|---|
| 2022-01-01 | 1649104 | PH | 2020-09-26 |
| 2022-01-01 | 1306498 | PH | 2020-09-26 |
| 2022-01-01 | 1290371 | PH | 2020-09-26 |
| 2022-01-01 | 456756 | TB | 2020-11-09 |
| 2022-01-01 | 1823713 | TB | 2020-11-09 |
| 2022-01-01 | 2178025 | BK | 2020-08-12 |
| 2022-01-01 | 216435 | BK | 2020-08-12 |
| 2022-01-01 | 19031 | BK | 2020-08-12 |
| 2022-01-01 | 438095 | BK | 2020-08-12 |
我使用的代码
SELECT Data , Brand , Customer_ID ,
(select top 1 first_value(H.Data) over (partition by Customer_ID , Brand order by H.Data ASC)
from ORDER H
where h.Customer_ID = Customer_ID and H.Brand = Brand
) as firts_order
from ORDER
LEFT OUTER JOIN ORDER_SOURCE SRC ON SRC.SRC_ID = ORDR_SOURCE
WHERE SRC_NAME IN (\'SR 1\' , \'SR 2\') and DATE = \'2022-01-01\'
标签: sql-server