如何在同一查询中多次将行添加到特定数字
Posted
技术标签:
【中文标题】如何在同一查询中多次将行添加到特定数字【英文标题】:How to add rows to a specific number multiple times in the same query 【发布时间】:2021-11-25 03:14:41 【问题描述】:我已经就我的部分问题here寻求帮助。
我过去不管有没有填满都是 10 行。但现在我面临其他事情,我需要在同一个查询结果中多次执行。
WITH NUMBERS AS
(
SELECT 1 rowNumber
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
)
SELECT DISTINCT sp.SLC_ID, c.rowNumber, c.PCE_ID
FROM SELECT_PART sp
LEFT JOIN (
SELECT b.*
FROM NUMBERS
LEFT OUTER JOIN (
SELECT a.*
FROM (
SELECT SELECT_PART.SLC_ID, ROW_NUMBER() OVER (ORDER BY SELECT_PART.SLC_ID) as
rowNumber, SELECT_PART.PCE_ID
FROM SELECT_PART
WHERE SELECT_PART.SLC_ID = (must be the same as sp.SLC_ID and can''t hardcode it)
) a
) b
ON b.rowNumber = NUMBERS.rowNumber
) c ON c.SLC_ID = sp.SLC_ID
ORDER BY sp.SLC_ID, c.rowNumber
前 10 行运行良好,但下一个 SLC_ID 只得到 1 个空行
我需要它是这样的
SLC_ID rowNumer PCE_ID
1 1 0001
1 2 0002
1 3 NULL
1 ... ...
1 10 NULL
2 1 0011
2 2 0012
2 3 0013
2 ... ...
2 10 0020
3 1 0021
3 ... ...
确实需要这种方式来构建报告。
【问题讨论】:
【参考方案1】:创建一个数字表,而不是手动构建一个特定于查询的数字列表,其中您必须包含您需要的每个可能的数字(在本例中为 1 到 10)。
DECLARE @UpperBound INT = 1000000;
;WITH cteN(Number) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY s1.[object_id]) - 1
FROM sys.all_columns AS s1
CROSS JOIN sys.all_columns AS s2
)
SELECT [Number] INTO dbo.Numbers
FROM cteN WHERE [Number] <= @UpperBound;
CREATE UNIQUE CLUSTERED INDEX CIX_Number ON dbo.Numbers([Number])
WITH
(
FILLFACTOR = 100, -- in the event server default has been changed
DATA_COMPRESSION = ROW -- if Enterprise & table large enough to matter
);
Source: mssqltips
或者,由于您无法添加数据,请使用 SQL Server 中已存在的表。
WITH NUMBERS AS
(
SELECT DISTINCT Number as rowNumber FROM master..spt_values where type = 'P'
)
SELECT DISTINCT sp.SLC_ID, c.rowNumber, c.PCE_ID
FROM SELECT_PART sp
LEFT JOIN (
SELECT b.*
FROM NUMBERS
LEFT OUTER JOIN (
SELECT a.*
FROM(
SELECT SELECT_PART.SLC_ID, ROW_NUMBER() OVER (ORDER BY SELECT_PART.SLC_ID) as
rowNumber, SELECT_PART.PCE_ID
FROM SELECT_PART
WHERE SELECT_PART.SLC_ID = (must be the same as sp.SLC_ID and can''t hardcode it)
) a
) b
ON b.rowNumber = NUMBERS.rowNumber
) c ON c.SLC_ID = sp.SLC_ID
ORDER BY sp.SLC_ID, c.rowNumber
注意:此解决方案的最大值为 2047
【讨论】:
我无法更改数据库结构。即使临时存储数据,我也不允许创建索引或表 @EricBrochu 将10
更改为0
,您可以多次使用从现有NUMBERS
CTE 到自身的CROSS JOIN 快速生成任意大的数字集合.
@EricBrochu,你能做到WITH NUMBERS AS (SELECT DISTINCT number from master..spt_values where type = 'P')
吗?以上是关于如何在同一查询中多次将行添加到特定数字的主要内容,如果未能解决你的问题,请参考以下文章