如何在计算SpelementUnit
元素数量的部分(SpelementElement_Count列)改进这段代码?
我需要一个 SpelementUnit 的序列单独计数,而不是在整个 XML 中进行连续计数。
(在每个 EntitySpatial
内 --> SpatialElement
元素)
虽然这段代码从 1 数到 7。当我需要 1,2 - 1,2,3 - 1,2 时
代码
DECLARE @xml XML =
N'<Parcels>
<Parcel ID="1">
<EntitySpatial>
<SpatialElement>
<SpelementUnit>
<Ordinate X="100.1" Y="-100.1"/>
</SpelementUnit>
<SpelementUnit>
<Ordinate X="100.2" Y="-100.2"/>
</SpelementUnit>
</SpatialElement>
<SpatialElement>
<SpelementUnit>
<Ordinate X="100.3" Y="-100.3"/>
</SpelementUnit>
<SpelementUnit>
<Ordinate X="100.4" Y="-100.4"/>
</SpelementUnit>
<SpelementUnit>
<Ordinate X="100.5" Y="-100.5"/>
</SpelementUnit>
</SpatialElement>
</EntitySpatial>
</Parcel>
<Parcel ID="2">
<EntitySpatial>
<SpatialElement>
<SpelementUnit>
<Ordinate X="200.1" Y="-200.1"/>
</SpelementUnit>
<SpelementUnit>
<Ordinate X="200.2" Y="-200.2"/>
</SpelementUnit>
</SpatialElement>
</EntitySpatial>
</Parcel>
</Parcels>';
SELECT base.value('@ID', 'VARCHAR(1000)') AS Parcel_ID
, DENSE_RANK() OVER(ORDER BY outr) as SpatialElement_Count
-- ,outr2.value('@PointNum', 'NVARCHAR(1000)') AS PointNum
,outr2.value('(Ordinate/@X)[1]', 'NVARCHAR(1000)') AS Ordinate_X
,outr2.value('(Ordinate/@Y)[1]', 'NVARCHAR(1000)') AS Ordinate_Y
, DENSE_RANK() OVER(ORDER BY outr2) as SpelementElement_Count
FROM @xml.nodes('Parcels/Parcel') as x(base)
OUTER APPLY base.nodes('EntitySpatial/SpatialElement') AS B(outr)
OUTER APPLY outr.nodes('SpelementUnit') AS C(outr2);
期望的输出(主列是“SpelementElement_Count”)
+-----------+---------------------+----- -----+------------+------------------------+
| Parcel_ID | SpatialElement_Count | Ordinate_X | Ordinate_Y | SpelementElement_Count |
+-----------+----------------------+------------+------------+------------------------+
| 1 | 1 | 100.1 | -100.1 | 1 |
| 1 | 1 | 100.2 | -100.2 | 2 |
| 1 | 2 | 100.3 | -100.3 | 1 |
| 1 | 2 | 100.4 | -100.4 | 2 |
| 1 | 2 | 100.5 | -100.5 | 3 |
| 2 | 3 | 200.1 | -200.1 | 1 |
| 2 | 3 | 200.2 | -200.2 | 2 |
+-----------+----------------------+------------+------------+------------------------+
最佳答案
当 OVER 时,您可以使用 PARTITION BY
使用子句。它只是
Divides the query result set into partitions. The window function is applied to each partition separately and computation restarts for each partition.
您可以将 OVER
子句中的 PARTITION BY
视为使用聚合函数时的 GROUP BY
子句。
SELECT base.value('@ID', 'VARCHAR(1000)') AS Parcel_ID
, DENSE_RANK() OVER(ORDER BY outr) as SpatialElement_Count
,outr2.value('(Ordinate/@X)[1]', 'NVARCHAR(1000)') AS Ordinate_X
,outr2.value('(Ordinate/@Y)[1]', 'NVARCHAR(1000)') AS Ordinate_Y
, DENSE_RANK() OVER(PARTITION BY outr ORDER BY outr2) as SpelementElement_Count
FROM @xml.nodes('Parcels/Parcel') as x(base)
OUTER APPLY base.nodes('EntitySpatial/SpatialElement') AS B(outr)
OUTER APPLY outr.nodes('SpelementUnit') AS C(outr2);
关于sql - 对 XML 节点中的每个元素进行计数,而不是连续计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64333367/