如果另一列中的计数大于1,则将同一行列出两次

时间:2017-10-04 21:03:05

标签: sql sql-server tsql ssms ranking

我遇到了这个要求,如果相应的列值大于1,则在输出中列出两次。

Calls       Abandoned
Microsoft   1
Apple       1
IBM         2
CISCO       3

Output Needed:
Calls       Abandoned
Microsoft   1
Apple       1
IBM         1
IBM         1
CISCO       1
CISCO       1
CISCO       1
我尝试在sql中使用排名功能,似乎没有用。任何解决方案的家伙?

2 个答案:

答案 0 :(得分:4)

一种方法使用数字表或CTE。或者,如果给定的call只有少量行,那么递归CTE就足够了:

with cte as (
      select call, abandoned
      from t
      union all
      select call, abandoned - 1
      from cte
      where abandoned > 1
    )
select call, 1 as abandoned
from cte;

call行最多100行。之后,您需要将MAXRECURSION设置为更高的值。

编辑:

这是rextester

答案 1 :(得分:0)

另一种方法是使用master..spt_values

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/b5f13a70-6ff5-4704-83d6-e1cd68f172b5/select-the-numbers-between-two-numbers?forum=transactsql

declare @mytable table (calls varchar(20), abandoned smallint)

insert into @mytable
values ('Microsoft',   1),
('Apple',       1),
('IBM',         2),
('CISCO',       3)

select calls,1 [Abandoned]  from @mytable t
   cross apply
   ( SELECT DISTINCT number
    FROM master..spt_values
    WHERE number BETWEEN 1 AND t.abandoned
   ) x


-- or simplest

SELECT  t1.calls, 1 [abandoned]
FROM    @mytable t1
JOIN    master.dbo.spt_values t2 on type = 'P' and number < t1.abandoned

<强>&GT;但是master.dbo.spt_values数量最多只有2048

CTE将是最佳答案。