List Lines per Quantity(按数量列出行)
问题描述
我可能想多了.我有一个带有 Name 和 Ticket Quantity 列的简单表格.我想逐行输出每个购买数量的名称列表.请参阅下面的示例.
I'm probably over thinking this. I have a simple table with Name and Ticket Quantity columns. I want to output a row by row list of the names for each quantity purchased. See example below.
表格:
Name Quantity
-----------------------
Bob 1
Joe 2
Sally 1
输出:
Bob
Joe
Joe
Sally
我如何在 TSQL 中实现这一点?
How could I achieve this in TSQL?
推荐答案
SETUP:
DECLARE @table TABLE (
NAME VARCHAR(10),
Quantity INT
)
INSERT INTO @table
SELECT 'Bob', 1 UNION ALL
SELECT 'Joe', 2 UNION ALL
SELECT 'Sally', 1
递归 CTE
;WITH Members (
NAME,
Quantity
)
AS (
-- Base case
SELECT NAME,
Quantity
FROM @table
UNION ALL
-- Recursive
SELECT NAME,
Members.Quantity - 1
FROM Members
WHERE Members.Quantity > 1
)
SELECT NAME
FROM Members
OPTION (MAXRECURSION 0)
ORDER BY 1
结果:
Bob
Joe
Joe
Sally
<小时>
或者你可以(根据@Martin Smith 的建议):
Alternatively you could (per @Martin Smith's suggestion):
DECLARE @numbers TABLE (number INT)
INSERT INTO @numbers (number)
VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)
最后:
SELECT NAME
FROM @table t
INNER JOIN @numbers n ON n.number <= t.Quantity
ORDER BY 1
结果:
Bob
Joe
Joe
Sally
<小时>如果你真的喜欢递归 CTE(因为它们闻起来很香),你可以用递归 CTE 构建你的数字表.您应该使用物理表,而不是您在此处看到的变量表 - 这样您就不必每次都构建它们.
And if you really like recursive CTE's (because they smell good), you could build your numbers table with a recursive CTE. You should be using physical tables and not variable tables as you see here - so that you don't have to build them every time.
;WITH Numbers (Value)
AS (
-- Base case
SELECT 32767 Value
UNION ALL
-- Recursive
SELECT Numbers.Value - 1
FROM Numbers
WHERE Numbers.Value > 1
)
INSERT INTO @numbers (number)
SELECT Value
FROM Numbers
OPTION (MAXRECURSION 32767)
这篇关于按数量列出行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:按数量列出行
基础教程推荐
- 带更新的 sqlite CTE 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
