如何通过从多个订单项中获取值来创建 header 条记录?

How can I create header records by taking values from one of several line items?

我有一组已排序的订单项。它们首先按 ID 排序,然后按 Date:

排序
| ID  | DESCRIPTION |   Date   |
| --- | ----------- |----------|
| 100 | Red         |2019-01-01|
| 101 | White       |2019-01-01|
| 101 | White_v2    |2019-02-01|
| 102 | Red_Trim    |2019-01-15|
| 102 | White       |2019-01-16|
| 102 | Blue        |2019-01-20|
| 103 | Red_v3      |2019-01-14|
| 103 | Red_v3      |2019-03-14|

我需要在代表项目 header 的 SQL 服务器 table 中插入行,以便每个 ID 的第一行提供 DescriptionDate 在目的地 table。对于每个 ID,目的地 table 中应该只有一行。

例如,上面的来源 table 会在目的地产生这样的结果:

| ID  | DESCRIPTION |   Date   |
| --- | ----------- |----------|
| 100 | Red         |2019-01-01|
| 101 | White       |2019-01-01|
| 102 | Red_Trim    |2019-01-15|
| 103 | Red_v3      |2019-01-14|

如何折叠源代码以便我只从源代码中获取每个 ID 的第一行?

我更喜欢在 SSIS 中进行转换,但如有必要可以使用 SQL。实际上,这两种方法的解决方案都是最有帮助的。


这个问题不同于 Trouble using ROW_NUMBER() OVER (PARTITION BY …) 因为这试图确定一种方法。该问题的提问者采用了一种方法,这里的答案确定了不止一种可用方法。这个问题是关于如何使该特定方法起作用。

使用first_valuewindow函数

select * from (select *,
first_value(DESCRIPTION) over(partition by id order by Date) as des,
row_number() over(partition by id order by Date) rn
from table
) a where a.rn =1

相关子查询将在此处提供帮助:

 SELECT *
 FROM yourtable t1
 WHERE [Date] = (SELECT min([Date]) FROM yourtable WHERE id = t1.id)

您可以使用 ROW_NUMBER() window 函数来执行此操作。例如:

select *
from (
  select
    id, description, date,
    row_number() over(partition by id order by date) as rn
  from t
)
where rn = 1

您可以使用 row_number() :

select t.*
from (select t.*, row_number() over (partition by id order by date) as seq
      from table t
     ) t
where seq = 1;