Recursive cte to repeat several integers - sql

I'd like a column of numbers:
Seven occurances of the integer 1, followed by 7 occurances of 2, followed by 7 occurances of 3 .... , followed by 7 occurances of n-1, followed by 7 occurances of n. Like so
Num
1
1
1
1
1
1
1
2
2
2
2
2
2
2
...
...
n-1
n-1
n-1
n-1
n-1
n-1
n-1
n
n
n
n
n
n
n
Unfortunately I've not progressed too far. My current attempt is the following, where n=4:
WITH
one AS
(
SELECT num = 1,
cnt = 0
UNION ALL
SELECT num = num,
cnt = cnt + 1
FROM one
WHERE cnt < 7
),
x AS
(
SELECT num,
cnt = 0
FROM one
UNION ALL
SELECT num = num + 1,
cnt = cnt + 1
FROM one
WHERE cnt < 4
)
SELECT *
FROM x

;WITH Numbers AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM Numbers
WHERE n+1 <= 10
),
se7en AS
(
SELECT n = 1
UNION ALL
SELECT n + 1
FROM se7en
WHERE n+1 <= 7
)
SELECT Numbers.n
FROM Numbers CROSS JOIN se7en

with x as
(select 1 as id
union all
select 2 as id
union all
select 3 as id
union all
select 4 as id
union all
select 5 as id
union all
select 6 as id
union all
select 7 as id)
select x1.* from x cross join x x1
The cross join will work in your case.

No need to use recursive CTE for this you can try set based approach solution try something like this. Kind of integer division.
If you have access to master database then use this.
;with cte as
(
SELECT top 1000 [7_seq] = ( ( Row_number()OVER(ORDER BY (SELECT NULL)) - 1 ) / 7 ) + 1
FROM sys.columns
)
select * from cte where [7_seq] <= #n
or use tally table to generate the numbers. I will prefer this solution
DECLARE #n INT = 10;
WITH Tally (num)
AS (
-- 1000 rows
SELECT Row_number()OVER (ORDER BY (SELECT NULL))
FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)),
seq
AS (SELECT [7_seq] = ( ( Row_number()
OVER(
ORDER BY (SELECT num)) - 1 ) / 7 ) + 1
FROM Tally)
SELECT [7_seq]
FROM seq
WHERE [7_seq] <= #n

WITH t1 AS (SELECT 0 as num UNION ALL SELECT 0)
,t2 AS (SELECT 0 as num FROM t1 as a CROSS JOIN t1 as b)
,t3 AS (SELECT 0 as num FROM t2 as a CROSS JOIN t2 as b)
,t4 AS (SELECT 0 as num FROM t3 as a CROSS JOIN t3 as b)
,Tally (number)
AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) FROM t4)
SELECT t1.number
FROM Tally as t1 cross join Tally as t2
where t2.number <=7
ORDER BY t1.number;

You can do It in following:
DECLARE #num INT = 1,
#sub INT = 0,
#max INT = 10,
#timesToRepeat INT = 7
CREATE TABLE #Temp (num INT)
WHILE (#num < #max + 1)
BEGIN
SET #sub = 0;
WHILE (#sub < #timesToRepeat)
BEGIN
INSERT INTO #Temp
SELECT #num x
SET #sub = #sub +1
END
SET #num = #num +1
END
SELECT * FROM #Temp
DROP TABLE #Temp
Set #max variable to number what you want to reach for now It is 10 so It will return result set like:
1
1
1
1
1
1
1
2
2
2
2
2
2
2
.
.
.
10
10
10
10
10
10
10

DECLARE #MAX INTEGER
SET #MAX = 5;
with cte as
(SELECT 7 as num
UNION ALL
SELECT num-1 as num from cte where num>1
),cte2 AS
(SELECT #MAX as num
UNION ALL
SELECT num-1 as num from cte2 where num>1)
select C2.num from cte C1,cte2 C2 ORDER by C2.num asc
Change the value of #MAX to reflect the value of n

Here is a slightly different way to do it.
select null num into #a
union all
select null
union all
select null
union all
select null
union all
select null
union all
select null
union all
select null
select * into #b from
(select rn = row_number()over (order by (select null)) from sys.objects A cross join sys.objects B) A
where rn <=10
select #b.rn as numbers from #a cross join #b
order by 1

Related

SQL Grouping by first digit from sets of record

I need your help in SQL
I have a set of records of Cost center ID below.
what I want to do is to segregate/group them by inserting column to distinguish the category.
as you can see all digits start in 7 is belong to the bold digits.
my expected out is on below image also.
You can as the below:
DECLARE #Tbl TABLE (ID INT)
INSERT INTO #Tbl
VALUES
(735121201),
(735120001),
(5442244),
(735141094),
(735141097),
(4008060),
(735117603),
(40100000),
(735142902),
(735151199),
(4010070)
;WITH TableWithRowId
AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY(SELECT NULL)) RowId,
ID
FROM
#Tbl
), TempTable
AS
(
SELECT T.RowId + 1 AS RowId FROM TableWithRowId T
WHERE
LEFT(T.ID, 1) != 7
), ResultTable
AS
(
SELECT
T.RowId ,
T.ID,
DENSE_RANK() OVER (ORDER BY (SELECT TOP 1 A.RowId FROM TempTable A WHERE A.RowId > T.RowId ORDER BY A.RowId)) AS Flag
FROM TableWithRowId T
)
SELECT * FROM ResultTable
Result:
RowId ID Flag
----------- ----------- ----------
1 735121201 1
2 735120001 1
3 5442244 1
4 735141094 2
5 735141097 2
6 4008060 2
7 735117603 3
8 40100000 3
9 735142902 4
10 735151199 4
11 4010070 4
The following query is similer with NEER's
;WITH test_table(CenterID)AS(
SELECT '735121201' UNION ALL
SELECT '735120001' UNION ALL
SELECT '5442244' UNION ALL
SELECT '735141094' UNION ALL
SELECT '735141097' UNION ALL
SELECT '4008060' UNION ALL
SELECT '735117603' UNION ALL
SELECT '40100000' UNION ALL
SELECT '735142902' UNION ALL
SELECT '735151199' UNION ALL
SELECT '4010070'
),t1 AS (
SELECT *,ROW_NUMBER()OVER(ORDER BY(SELECT 1)) AS rn,CASE WHEN LEFT(t.CenterID,1)='7' THEN 1 ELSE 0 END AS isSeven
FROM test_table AS t
),t2 AS(
SELECT t1.*,ROW_NUMBER()OVER(ORDER BY t1.rn) AS toFilter
FROM t1 LEFT JOIN t1 AS pt ON pt.rn=t1.rn-1
WHERE pt.CenterID IS NULL OR (t1.isSeven=1 AND pt.isSeven=0)
)
SELECT t1.CenterID,x.toFilter FROM t1
CROSS APPLY(SELECT TOP 1 t2.toFilter FROM t2 WHERE t2.rn<=t1.rn ORDER BY rn desc) x
CenterID toFilter
--------- --------------------
735121201 1
735120001 1
5442244 1
735141094 2
735141097 2
4008060 2
735117603 3
40100000 3
735142902 4
735151199 4
4010070 4

Is it possible to write a sql query that is grouped based on a running total of a column?

It would be easier to explain with an example. Suppose I wanted to get at most 5 items per group.
My input would be a table looking like this:
Item Count
A 2
A 3
A 3
B 4
B 4
B 5
C 1
And my desired output would look like this:
Item Count
A 5
A>5 3
B 4
B>5 9
C 1
An alternative output that I could also work with would be
Item Count RunningTotal
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
I can use ROW_NUMBER() to get the top X records in each group, however my requirement is to get the top X items for each group, not X records. My mind is drawing a blank as to how to do this.
declare #yourTable table (item char(1), [count] int)
insert into #yourTable
select 'A', 2 union all
select 'A', 3 union all
select 'A', 3 union all
select 'B', 4 union all
select 'B', 4 union all
select 'B', 5 union all
select 'C', 1
;with cte(item, count, row) as (
select *, row_number() over ( partition by item order by item, [count])
from #yourTable
)
select t1.Item, t1.Count, sum(t2.count) as RunningTotal from cte t1
join cte t2 on t1.item = t2.item and t2.row <= t1.row
group by t1.item, t1.count, t1.row
Result:
Item Count RunningTotal
---- ----------- ------------
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
Considering the clarifications from your comment, you should be able to produce the second kid of output from your post by running this query:
select t.Item
, t.Count
, (select sum(tt.count)
from mytable tt
where t.item=tt.item and (tt.creating_user_priority < t.creating_user_priority or
( tt.creating_user_priority = t.creating_user_priority and tt.created_date < t.createdDate))
) as RunningTotal
from mytable t
declare #yourTable table (item char(1), [count] int)
insert into #yourTable
select 'A', 2 union all
select 'A', 3 union all
select 'A', 3 union all
select 'B', 4 union all
select 'B', 4 union all
select 'B', 5 union all
select 'C', 1
;with cte(item, count, row) as (
select *, row_number() over ( partition by item order by item, [count])
from #yourTable
)
select t1.row, t1.Item, t1.Count, sum(t2.count) as RunningTotal
into #RunTotal
from cte t1
join cte t2 on t1.item = t2.item and t2.row <= t1.row
group by t1.item, t1.count, t1.row
alter table #RunTotal
add GrandTotal int
update rt
set GrandTotal = gt.Total
from #RunTotal rt
left join (
select Item, sum(Count) Total
from #RunTotal rt
group by Item) gt
on rt.Item = gt.Item
select Item, max(RunningTotal)
from #RunTotal
where RunningTotal <= 5
group by Item
union
select a.Item + '>5', total - five
from (
select Item, max(GrandTotal) total
from #RunTotal
where GrandTotal > 5
group by Item
) a
left join (
select Item, max(RunningTotal) five
from #RunTotal
where RunningTotal <= 5
group by Item
) b
on a.Item = b.Item
I've updated the accepted answer and got your desired result.
SELECT Item, SUM(Count)
FROM mytable t
GROUP BY Item
HAVING SUM(Count) <=5
UNION
SELECT Item, 5
FROM mytable t
GROUP BY Item
HAVING SUM(Count) >5
UNION
SELECT t2.Item + '>5', Sum(t2.Count) - 5
FROM mytable t2
GOUP BY Item
HAVING SUM(Count) > 5
ORDER BY 1, 2
select 'A' as Name, 2 as Cnt
into #tmp
union all select 'A',3
union all select 'A',3
union all select 'B',4
union all select 'B',4
union all select 'B',5
union all select 'C',1
select Name, case when sum(cnt) > 5 then 5 else sum(cnt) end Cnt
from #tmp
group by Name
union
select Name+'>5', sum(cnt)-5 Cnt
from #tmp
group by Name
having sum(cnt) > 5
Here is what I have so far. I know it's not complete but... this should be a good starting point.
I can get your second output by using a temp table and an update pass:
DECLARE #Data TABLE
(
ID INT IDENTITY(1,1) PRIMARY KEY
,Value VARCHAR(5)
,Number INT
,Total INT
)
INSERT INTO #Data (Value, Number) VALUES ('A',2)
INSERT INTO #Data (Value, Number) VALUES ('A',3)
INSERT INTO #Data (Value, Number) VALUES ('A',3)
INSERT INTO #Data (Value, Number) VALUES ('B',4)
INSERT INTO #Data (Value, Number) VALUES ('B',4)
INSERT INTO #Data (Value, Number) VALUES ('B',5)
INSERT INTO #Data (Value, Number) VALUES ('C',1)
DECLARE
#Value VARCHAR(5)
,#Count INT
UPDATE #Data
SET
#Count = Total = CASE WHEN Value = #Value THEN Number + #Count ELSE Number END
,#Value = Value
FROM #Data AS D
SELECT
Value
,Number
,Total
FROM #Data
There may be better ways, but this should work.

Split a string into individual characters in Sql Server 2005

Hi I have an input as
ID data
1 hello
2 sql
The desired output being
ID RowID Chars
1 1 H
1 2 e
1 3 l
1 4 l
1 5 o
2 1 s
2 2 q
2 3 l
My approach so far being
Declare #t table(ID INT IDENTITY , data varchar(max))
Insert into #t Select 'hello' union all select 'sql'
--Select * from #t
;With CteMaxlen As(
Select MaxLength = max(len(data)) from #t)
, Num_Cte AS
(
SELECT 1 AS rn
UNION ALL
SELECT rn +1 AS rn
FROM Num_Cte
WHERE rn <(select MaxLength from CteMaxlen)
)
-- Shred into individual characters
, Get_Individual_Chars_Cte AS
(
SELECT
ID
,Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID)
,chars
FROM #t,Num_Cte
CROSS APPLY( SELECT SUBSTRING((select data from #t),rn,1) AS chars) SplittedChars
)
Select * from Get_Individual_Chars_Cte
The query is not working at all with an exception being
Msg 512, Level 16, State 1, Line 4
Subquery returned more than 1 value.
This is not permitted when the
subquery follows =, !=, <, <= , >, >=
or when the subquery is used as an
expression.
Edit :
I found my answer
;with Get_Individual_Chars_Cte AS
(
SELECT
ID,
Row_ID =ROW_NUMBER() Over(PARTITION by ID Order by ID)
,SUBSTRING(Data,Number,1) AS [Char]--,
FROM #t
INNER JOIN master.dbo.spt_values ON
Number BETWEEN 1 AND LEN(Data)
AND type='P'
)
Select * from Get_Individual_Chars_Cte
Help needed
;with cte as
(
select ID,
substring(data, 1, 1) as Chars,
stuff(data, 1, 1, '') as data,
1 as RowID
from #t
union all
select ID,
substring(data, 1, 1) as Chars,
stuff(data, 1, 1, '') as data,
RowID + 1 as RowID
from cte
where len(data) > 0
)
select ID, RowID, Chars
from cte
order by ID, RowID
Old post but it's worth posting a purely set-based solution. Using NGrams8K you can do this:
Declare #t table(ID INT IDENTITY , data varchar(max))
Insert into #t Select 'hello' union all select 'sql';
SELECT ID, Row_ID = position, [char] = token
FROM #t
CROSS APPLY dbo.NGrams8k(data,1);
Returns:
ID Row_ID char
--- ------- --------
1 1 h
1 2 e
1 3 l
1 4 l
1 5 o
2 1 s
2 2 q
2 3 l

How to find the nth Term in tsql

I have a table as under
Term
0
8
24
48
80
X
The desired output being
Term1 Term2 Diff
0 8 8
8 24 16
24 48 24
48 80 32
80 x 40
I have the below script
Declare #t Table(Term varchar(10))
Insert Into #t
Select '0' Union All
Select '8' Union All
Select '24' Union All
Select '48' Union All
Select '80' Union All
Select 'X'
So far I have tried as
;With Cte1 As
(
Select rn = ROW_NUMBER() Over(Order By (select 1)),* From #t
)
,cte2 as(
Select
Term1 = (Select term from Cte1 where rn=1)
,Term2 = (Select term from Cte1 where rn=2)
,Diff = Cast((Select term from Cte1 where rn=2) as int) - Cast((Select term from Cte1 where rn=1) as int)
)
Select * from cte2
I donot know what to do in the recursive part of cte2..
Help needed
I'm unsure why the difference between 80 and x is supposed to be 40, but you can handle that by tweaking the CTE to return what you need for the last row.
;WITH Cte1 AS
(
SELECT rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1)), * FROM #t
)
SELECT
Term1 = Cte1.Term,
Term2 = (SELECT Term FROM Cte1 AS a_CTE where a_CTE.rn = Cte1.rn + 1),
Diff = CAST((SELECT CASE Term WHEN 'X' THEN 120 ELSE Term END
FROM Cte1 AS a_CTE
WHERE a_CTE.rn = Cte1.rn + 1) AS int)
- CAST(Cte1.Term AS int)
FROM Cte1
WHERE ISNUMERIC(Cte1.Term) = 1
I recommend using PIVOT and not a recursive CTE. Cf.: http://msdn.microsoft.com/en-us/library/ms177410.aspx

SQL field = other field minus another row

Table has 2 cols: [nr] and [diff]
diff is empty (so far - need to fill)
nr has numbers:
1
2
45
677
43523452
on the diff column i need to add the differences between pairs
1 | 0
2 | 1
45 | 43
677 | 632
43523452 | 43522775
so basically something like :
update tbl set diff = #nr - #nrold where nr = #nr
but i don't want to use fetch next, because it's not cool, and it's slow (100.000) records
how can I do that with one update?
CREATE TABLE #T(nr INT,diff INT)
INSERT INTO #T (nr) SELECT 1
UNION SELECT 2
UNION SELECT 45
UNION SELECT 677
UNION SELECT 43523452
;WITH cte AS
(
SELECT nr,diff, ROW_NUMBER() OVER (ORDER BY nr) RN
FROM #T
)
UPDATE c1
SET diff = ISNULL(c1.nr - c2.nr,0)
FROM cte c1
LEFT OUTER JOIN cte c2 ON c2.RN+1= c1.RN
SELECT nr,diff FROM #T
DROP TABLE #T
Have a look at something like this (full example)
DECLARE #Table TABLE(
nr INT,
diff INT
)
INSERT INTO #Table (nr) SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 45 UNION ALL
SELECT 677 UNION ALL
SELECT 43523452
;WITH Vals AS (
SELECT nr,
diff,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) xID
FROM #Table
)
UPDATE c
SET diff = c.nr - ISNULL(p.nr, 0)
FROM Vals c LEFT JOIN
Vals p ON c.xID = p.xID + 1
SELECT *
FROM #Table
try this -
update tablename
set diff = cast(nr as INT) - cast((select nr from tablename where diff is not null and nr = a.nr) as INT)
from tablename a
where diff is null
This is assuming you only have one older row for nr old in the table. else the subquery will return more than one value