sql查询根据请求的输出显示重复项

时间:2014-07-29 18:35:36

标签: sql-server

我有一个示例输入表,如下所示

╔═══════════╗
║ name   id ║
╠═══════════╣
║ anil    3 ║
║ ashok   2 ║
╚═══════════╝

我希望以

的形式获得此表的输出
╔════════════╗
║ name    id ║
╠════════════╣
║ anil     3 ║
║ anil     3 ║
║ anil     3 ║
║ ashok    2 ║
║ ashok    2 ║
╚════════════╝

如何使用sql查询实现这一点?

2 个答案:

答案 0 :(得分:1)

这似乎是递归CTE的工作:

create table #input (name varchar(10), id int)
insert into #input values ('anil',3),('ashok',2)

;with cte as
(   select a.name, a.id, a.id as countdown
    from #input a
    union all
    select a.name, a.id, a.countdown-1
    from cte a
    where a.countdown-1 > 0
)
select name,id,countdown from cte
order by 1,2,3 desc

输出

name   id  countdown
====================
anil    3      3
anil    3      2
anil    3      1
ashok   2      2
ashok   2      1

答案 1 :(得分:0)

尝试递归查询很有吸引力,但这可以通过计数表来完成。

这样的事情:

SET nocount ON; 

IF Object_id('dbo.Tally') IS NOT NULL 
  DROP TABLE dbo.tally 



-- Define how many rows you want in Tally table.  
-- I am inserting only 100 rows 
SET ROWCOUNT 100 

SELECT IDENTITY(int, 1, 1) ID 
INTO   dbo.tally 
FROM   master.sys.all_columns c 
       CROSS JOIN master.sys.all_columns c1 

-- you may use one more cross join if tally table required hundreds of million rows 
SET ROWCOUNT 0 

-- ADD (unique) clustered index 
CREATE UNIQUE CLUSTERED INDEX pkc_tally 
  ON dbo.tally (id) 


SELECT T2.* 
FROM   dbo.tally T1 
       CROSS JOIN table1 T2 
WHERE  T1.id <= T2.id 

你可以看看 SQL Fiddle

上的例子。