我希望根据同一行中的值返回重复的数据行。
请参考下表......
customer | noOfConnections
A | 1
B | 1
C | 2
D | 1
我想要一些sql来返回...
customer | connectionNumber
A | 1
B | 1
C | 1
C | 2
D | 1
有办法吗?
由于
答案 0 :(得分:0)
;with cTE as
(
select 'A' customer, 1 noOfConnections union all
select 'B', 1 union all
select 'C', 2 union all
select 'D', 1
)
, CTE1 as
(
select customer,noOfConnections from cte where noOfConnections>1
union all
select a.customer,a.noOfConnections-1 from cte A inner join cte1 B
on a.customer=b.customer and b.noOfConnections=a.noOfConnections
)
select * from cte1
union all
select * from cte where noOfConnections=1
答案 1 :(得分:0)
数字表,yayyy!
搜索脚本。或者here's one I made earlier。
SELECT your_table.customer
, your_table.noOfConnections
, numbers.number As connectionNumber
FROM your_table
INNER
JOIN dbo.numbers
ON numbers.number BETWEEN 1 AND your_table.noOfConnections
答案 2 :(得分:0)
试试这个
--Drop table Table1
CREATE TABLE Table1
([cust] varchar(1), [cn] int)
;
INSERT INTO Table1
VALUES
('A', 1),
('B', 1),
('C', 1),
('C', 2),
('D', 1),
('E', 4);
with cte as(
select Max(cn) CN,
cust
from Table1
group by cust
union all
select c1.Cn-1 CN,c1.cust from cte c1 join table1 T1 on c1.cust=t1.cust
where c1.cn-1>0
)
select * from cte
order by cust,cn
答案 3 :(得分:0)
具有表值函数的CTE在此处运行良好。只需用您可以遇到的最大数量替换10即可。
WITH q AS
(
SELECT 1 AS maxNum
UNION ALL
SELECT maxNum + 1
FROM q
WHERE maxNum < 10
)
SELECT Customer, maxNum as connectionNumber
FROM Customers
CROSS APPLY (SELECT * FROM q WHERE maxNum<=noOfConnections) temp
编辑:您可以返工CTE以从表中提取最大值,请参阅上面的答案: 所以这将是我的解决方案:
WITH q AS
(
SELECT Max(noOfConnections) AS maxNum
FROM Customers
UNION ALL
SELECT maxNum - 1
FROM q
WHERE maxNum > 1
)
SELECT Customer, maxNum as connectionNumber
FROM Customers
CROSS APPLY (SELECT * FROM q WHERE maxNum<=noOfConnections) temp