gpt4 book ai didi

SQL Server - 高级分组

转载 作者:行者123 更新时间:2023-12-03 00:25:16 25 4
gpt4 key购买 nike

我的表格包含如下所示的采购契约(Contract):

+------+-----------+------------+---------+------------+-----------+
| type | text | date | company | supplierID | name |
+ -----+-----------+------------+---------+------------+-----------+
| 0 | None | 2004-03-29 | 310 | 227234 | HRC INFRA |
| 0 | None | 2007-09-30 | 310 | 227234 | HRC INFRA |
| 0 | None | 2010-11-29 | 310 | 227234 | HRC INFRA |
| 2 | Strategic | 2011-01-01 | 310 | 227234 | HRC INFRA |
| 0 | None | 2012-04-10 | 310 | 227234 | HRC INFRA |
+------+-----------+------------+---------+------------+-----------+

在此示例中,契约(Contract)的前三行是相同的。所以我只想要第一个。type = 2 的行是与给定供应商的采购契约(Contract)的变更。我也想选择该行。在最后一行,合约变回 0,因此我也想选择该行。

基本上我想选择第一行和契约(Contract)类型发生变化的行。所以结果应该是这样的:

+------+-----------+------------+---------+------------+-----------+
| type | text | date | company | supplierID | name |
+ -----+-----------+------------+---------+------------+-----------+
| 0 | None | 2004-03-29 | 310 | 227234 | HRC INFRA |
| 2 | Strategic | 2011-01-01 | 310 | 227234 | HRC INFRA |
| 0 | None | 2012-04-10 | 310 | 227234 | HRC INFRA |
+------+-----------+------------+---------+------------+-----------+

对我如何实现这一目标有什么建议吗?

最佳答案

;WITH cte AS
(
SELECT ROW_NUMBER() OVER (ORDER BY date) AS Id,
type, text, date, company, supplierId, name
FROM your_table
)
SELECT c1.type, c1.text, c1.date, c1.company,
c1.supplierId, c1.name
FROM cte c1 LEFT JOIN cte c2 ON c1.id = c2.id + 1
WHERE c2.text IS NULL OR c1.text != c2.text

演示 SQLFiddle

关于SQL Server - 高级分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13971420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com