Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase 12»»

Solve Problems Using Recursive CTE Expand / Collapse
Author
Message
Posted Wednesday, December 5, 2012 12:41 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Thursday, December 13, 2012 6:34 PM
Points: 6, Visits: 58
Problem: Bank requires to find out number of months customs have spent money more then certain amount in consecutive month
or sales department requires to find out number of months a product has been sold more then certain amount in consecutive month.

If data is just in few months or just require for 2 or 3 consecutive months, then simple table join can do it.
But we have like years records, and need count all consecutive months, it will could be hard to hard coding all table join for 2, 3, 4 ,5 ... consecutive months.
There is an easy way using recursive CTE to solve such a problem.

For example, a table store sales records like below. And we need to list number of consecutive months for any sale who sold a product more then 2 in a month. It is can be done easily by following recursive CTE query

sample data
CREATE TABLE #sales(
[name] [varchar](50) NOT NULL,
[saledate] [datetime] NULL,
[quantity] [int] NULL
)

insert into #sales(name,saledate,quantity)
values
('A','2012-01-01',1),
('A','2012-02-01',2),
('A','2012-03-01',3),
('A','2012-04-01',4),
('A','2012-05-01',5),
('A','2012-06-01',6)

insert into #sales(name,saledate,quantity)
values
('B','2012-01-01',6),
('B','2012-02-01',2),
('B','2012-03-01',3),
('B','2012-04-01',4),
('B','2012-05-01',1),
('B','2012-06-01',6)

insert into #sales(name,saledate,quantity)
values
('C','2012-01-01',6),
('C','2012-02-01',1),
('C','2012-03-01',3),
('C','2012-04-01',1),
('C','2012-05-01',4),
('C','2012-06-01',1)

insert into #sales(name,saledate,quantity)
values
('D','2012-01-01',6),
('D','2012-02-01',3),
('D','2012-03-01',3),
('D','2012-04-01',4),
('D','2012-05-01',1),
('D','2012-06-01',6)

-- wm for all months in which product sold more 2
with wm as (
select name,saledate
from #sales
where quantity>2
),
-- only using above qualified records, not all records to do recursive join
base_cte (name,saledate ) as (
select * from wm
union all
select a.name,a.saledate
from wm a inner join base_cte b
on a.name=b.name and a.saledate=dateadd(month,1,b.saledate)
)

-- the count column indicates number of consecutive month for that month.
select b.name,b.saledate, COUNT(b.name) as cnt
from base_cte b
group by b.name,b.saledate
order by b.name,b.saledate

-- for example cnt = 2, meaning that month is the second month, from which, backward in 2
-- consecutive month, a product was sold more then 2 each month
-- cnt = 3, meaning that month is the third month, from which, backward in 3
-- consecutive month, a product was sold more then 2
Post #1393173
Posted Wednesday, December 5, 2012 3:04 PM


SSC Eights!

SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!SSC Eights!

Group: General Forum Members
Last Login: Friday, September 19, 2014 5:16 AM
Points: 887, Visits: 1,774
This looks like a gaps and island problem. it also from the problem description sounds like homework or an interview question.

Take a look at this for a detailed explanation and solution of the problem. http://www.manning.com/nielsen/nielsenMEAP_freeCh5.pdf Specifically part two chapter 5



For faster help in answering any problems Please read How to post data/code on a forum to get the best help - Jeff Moden for the best way to ask your question.

For performance Issues see how we like them posted here: How to Post Performance Problems - Gail Shaw

Need to Split some strings? Jeff Moden's DelimitedSplit8K
Jeff Moden's Cross tab and Pivots Part 1
Jeff Moden's Cross tab and Pivots Part 2

Jeremy Oursler
Post #1393236
Posted Wednesday, December 5, 2012 3:08 PM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: 2 days ago @ 11:51 AM
Points: 1,040, Visits: 3,106
Using Jeff Moden's article http://www.sqlservercentral.com/articles/T-SQL/71550/ about Group Islands of Contiguous Dates as inspiration, you could do the following

;WITH cte AS (
SELECT name,
DATEADD(mm, - ROW_NUMBER() OVER (ORDER BY name, saledate), saledate) dategroup,
saledate
FROM #sales
WHERE quantity > 2
)
SELECT name, MIN(saledate) firstsaledate, COUNT(*) cnt
FROM cte
GROUP BY name, dategroup
ORDER BY name, dategroup

Post #1393237
Posted Wednesday, December 5, 2012 3:37 PM


SSCommitted

SSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommittedSSCommitted

Group: General Forum Members
Last Login: Yesterday @ 4:26 PM
Points: 1,945, Visits: 3,025
Sales department requires to find out number of months a product has been sold more then certain amount in consecutive month.

If data is just in few months or just require for 2 or 3 consecutive months, then simple table join can do it.

But we have like years rows, and need count all consecutive months, it will could be hard to hard coding all table join for 2, 3, 4 , 5 ... consecutive months.
There is an easy way using recursive CTE to solve such a problem.

For example, a table store Sales rows like below. And we need to list number of consecutive months for any salesman who sold a product more then 2 in a month. It is can be done easily by following recursive CTE query

CREATE TABLE Sales
(salesman_name CHAR(10) NOT NULL,
sale_date CHAR(10) NOT NULL,
PRIMARY KEY (salesman_name, sale_date),
sale_qty INTEGER NOT NULL
CHECK (sale_qty > 0));

INSERT INTO Sales
VALUES
('A', '2012-01-00', 1), ('A', '2012-02-00', 2), ('A', '2012-03-00', 3),
('A', '2012-04-00', 4), ('A', '2012-05-00', 5), ('A', '2012-06-00', 6),

('B', '2012-01-00', 6), ('B', '2012-02-00', 2), ('B', '2012-03-00', 3),
('B', '2012-04-00', 4), ('B', '2012-05-00', 1), ('B', '2012-06-00', 6),

('C', '2012-01-00', 6), ('C', '2012-02-00', 1), ('C', '2012-03-00', 3),
('C', '2012-04-00', 1), ('C', '2012-05-00', 4), ('C', '2012-06-00', 1),

('D', '2012-01-00', 6), ('D', '2012-02-00', 3), ('D', '2012-03-00', 3),
('D', '2012-04-00', 4), ('D', '2012-05-00', 1), ('D', '2012-06-00', 6);

WITH X1
AS
(SELECT salesman_name, sale_date, sale_qty,
ROW_NUMBER() OVER (PARTITION BY salesman_name
ORDER BY salesman_name, sale_date) AS r1
FROM Sales),
X2
AS
(SELECT salesman_name, sale_date, sale_qty,
r1-
ROW_NUMBER() OVER (PARTITION BY salesman_name
ORDER BY salesman_name, sale_date)
AS sale_grp
FROM X1
WHERE sale_qty > 2)

SELECT salesman_name, MIN(sale_date), MAX(sale_date)
FROM X2
GROUP BY salesman_name, sale_grp;


Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Post #1393250
Posted Wednesday, December 5, 2012 4:04 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Thursday, December 13, 2012 6:34 PM
Points: 6, Visits: 58
I know Jeff Moden's solution.
But I assume this way could be faster because there is not sorting for row number.
At least, it is a different solution.
Post #1393260
Posted Wednesday, December 5, 2012 4:39 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 11:18 PM
Points: 35,267, Visits: 31,759
bj_shenglong (12/5/2012)
But I assume this way could be faster...


That's how rumors of performance get started.

Write code to build a million row test table and test your hypothesis. No matter which way it turns out, we'll all learn something if you post the results. See the following articles for how to do such a thing pretty easily and quickly.

http://www.sqlservercentral.com/articles/Data+Generation/87901/
http://www.sqlservercentral.com/articles/Test+Data/88964/


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1393267
Posted Wednesday, December 5, 2012 5:41 PM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Thursday, December 13, 2012 6:34 PM
Points: 6, Visits: 58
There is a particular problem, let's' say, we just want to find out who sold more then 2 each month in at least two consecutive months and when.

For the above sample, below recursion would work. Also, recursion will stop immediately when it reaches the first qualified date.

with m2_cte_f (name,saledate,quantity,ind) as (
select s.*, 0 as ind
from #sales s
where s.saledate='2012-01-01'
union all
select s.*, case when s.quantity > 2 and sc.quantity > 2 then 1 else 0 end as ind
from #sales s
inner join m2_cte_f sc
on (s.saledate = dateadd(month,1,sc.saledate) and s.name=sc.name)
where sc.ind = 0
)
select * from m2_cte_f where ind=1
Post #1393282
Posted Wednesday, December 5, 2012 8:13 PM
Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: 2 days ago @ 11:51 AM
Points: 1,040, Visits: 3,106
So comparing the islands and recursive queries returning similar rows

;WITH cte AS (
SELECT name,
DATEADD(mm, - ROW_NUMBER() OVER (ORDER BY name, saledate), saledate) dategroup,
saledate
FROM #sales
WHERE quantity > 2 and saledate >= '2012-01-01'
)
SELECT name, max(saledate), COUNT(*)
FROM cte
GROUP BY name, dategroup
HAVING COUNT(*) > 1
ORDER BY name, dategroup

;with m2_cte_f (name,saledate,quantity,ind) as (
select s.*, 0 as ind
from #sales s
where s.saledate='2012-01-01'
union all
select s.*, case when s.quantity > 2 and sc.quantity > 2 then 1 else 0 end as ind
from #sales s
inner join m2_cte_f sc
on (s.saledate = dateadd(month,1,sc.saledate) and s.name=sc.name)
where sc.ind = 0
)
select * from m2_cte_f where ind=1

I get the following IO stats (timing not worth mentioning 1ms each) for the small test set
(3 row(s) affected)
Table '#sales____00000000009F'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(3 row(s) affected)
Table 'Worktable'. Scan count 2, logical reads 91, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#sales____00000000009F'. Scan count 2, logical reads 14, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.



Upping the stakes a tiny bit by putting a moderate amount of data (3000 odd rows) into the table
INSERT INTO #sales (name, saledate)
SELECT *
FROM
(SELECT * FROM (VALUES('A'),('B'),('C'),('D'),('E'),('F'),('G'),('H'),('I'),('J'),('K'),('L'),('M'),('N'),('O'),('P'),('Q'),('R'),('S'),('T')) as sales(name)) names,
(SELECT TOP 156 dateadd(mm, N, '1999-12-01') saledate FROM Tally) as months

UPDATE #sales
SET quantity = RAND(Checksum(Newid())) * 5

CREATE CLUSTERED INDEX SALES_IDX1 ON #sales (saledate, name)

I get the following
(22 row(s) affected)
Table '#sales__0000000000A4'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.

(15 row(s) affected)
Table 'Worktable'. Scan count 2, logical reads 635, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#sales__0000000000A4'. Scan count 96, logical reads 193, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 3 ms.


As I added more rows to the table the recursive query got very gradually slower and did more reads, while the islands query remained static. I got up to 75816 rows. Would you believe the had sales data back to 1770 for the same 26 people
(27 row(s) affected)
Table '#sales__0000000000AD'. Scan count 1, logical reads 4, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 1 ms.

(19 row(s) affected)
Table 'Worktable'. Scan count 2, logical reads 1193, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#sales__0000000000AD'. Scan count 189, logical reads 380, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 5 ms.
Post #1393299
Posted Wednesday, December 5, 2012 9:22 PM


SSC-Dedicated

SSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-DedicatedSSC-Dedicated

Group: General Forum Members
Last Login: Yesterday @ 11:18 PM
Points: 35,267, Visits: 31,759
bj_shenglong (12/5/2012)
There is a particular problem, let's' say, we just want to find out who sold more then 2 each month in at least two consecutive months and when.

For the above sample, below recursion would work. Also, recursion will stop immediately when it reaches the first qualified date.


Although they can be fast, recursive CTEs are still procedural in nature. The only way to know for sure is to do a test.

{Edit} Was distracted by a code promotion going on at work and I see that MickyT made just such a test. Thank you, good Sir!


--Jeff Moden
"RBAR is pronounced "ree-bar" and is a "Modenism" for "Row-By-Agonizing-Row".

First step towards the paradigm shift of writing Set Based code:
Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column."

(play on words) "Just because you CAN do something in T-SQL, doesn't mean you SHOULDN'T." --22 Aug 2013

Helpful Links:
How to post code problems
How to post performance problems
Post #1393312
Posted Wednesday, December 5, 2012 10:32 PM
SSC Veteran

SSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC VeteranSSC Veteran

Group: General Forum Members
Last Login: Sunday, September 14, 2014 12:30 AM
Points: 253, Visits: 540
this is my contribution
USE tempdb
GO
IF OBJECT_ID('TestTbl') IS NOT NULL
DROP TABLE TestTbl

CREATE TABLE Testtbl (id INT PRIMARY KEY)

INSERT INTO Testtbl
(
id
)
SELECT TOP 1000 ROW_NUMBER() OVER ( ORDER BY c.object_id) id FROM sys.[columns] c ,sys.[columns] c2

DELETE FROM TestTbl WHERE id IN(SELECT top 100 ABS(CHECKSUM(NEWID())%1000) FROM sys.[columns] c)

DELETE FROM TestTbl WHERE id IN(SELECT top 100 ABS(CHECKSUM(NEWID())%1000) FROM sys.[columns] c)

SELECT * FROM TestTbl;

WITH S AS (
SELECT ROW_NUMBER() OVER (order by t.id) AS RN,t.id
FROM TestTbl t LEFT OUTER JOIN TestTbl t2
ON t.id -1= t2.id
WHERE t2.id IS NULL
),E AS (
SELECT ROW_NUMBER() OVER (order by t.id) AS RN, t.id
FROM TestTbl t LEFT OUTER JOIN TestTbl t2
ON t.id +1= t2.id
WHERE t2.id IS NULL
)

SELECT s.id AS [START], e.id AS [END] FROM S INNER JOIN E ON s.Rn= E.rn
GO

using this i try to solve your problem
USE tempdb
GO

IF OBJECT_ID('sales') IS NOT NULL
DROP TABLE sales
CREATE TABLE sales(
[name] [varchar](50) NOT NULL,
[saledate] [datetime] NULL,
[quantity] [int] NULL
)
GO
Insert into sales(name,saledate,quantity)
values
('A','2012-01-01',1),('A','2012-02-01',2),('A','2012-03-01',3),
('A','2012-04-01',4),('A','2012-05-01',5),('A','2012-06-01',6),

('B','2012-01-01',6),('B','2012-02-01',2),('B','2012-03-01',3),
('B','2012-04-01',4),('B','2012-05-01',1),('B','2012-06-01',6),

('C','2012-01-01',6),('C','2012-02-01',1),('C','2012-03-01',3),
('C','2012-04-01',1),('C','2012-05-01',4),('C','2012-06-01',1),

('D','2012-01-01',6),('D','2012-02-01',3),('D','2012-03-01',3),
('D','2012-04-01',4),('D','2012-05-01',1),('D','2012-06-01',6);
WITH Fil AS (
SELECT *
FROM sales
WHERE quantity > 2
),
S AS (
SELECT ROW_NUMBER() OVER (ORDER BY t.name) AS RN, t.NAME, MONTH (t.saledate) AS id
FROM Fil t
LEFT OUTER JOIN Fil t2
ON MONTH (t.saledate) -1 = MONTH (t2.saledate) AND
t2.name = t.name
WHERE t2.saledate IS NULL
),
E AS (
SELECT ROW_NUMBER() OVER (ORDER BY t.name) AS RN, t.NAME, MONTH (t.saledate) AS id
FROM Fil t
LEFT OUTER JOIN Fil t2
ON MONTH (t.saledate) + 1 = MONTH (t2.saledate) AND
t2.name = t.name
WHERE t2.saledate IS NULL
),
Gap AS(
SELECT e.NAME, s.id AS [DateStart], e.id AS [DateEnd]
FROM S
INNER JOIN E
ON s.Rn = E.rn
--AND s.id<>e.id
)

SELECT g.NAME ,g.Datestart, sum(CASE WHEN(sales.quantity>2) AND MONTH(sales.saledate) BETWEEN g.datestart AND g.dateend THEN 1 ELSE 0 END ) as Res
FROM sales INNER JOIN gap g ON sales.name =g.NAME AND month(sales.saledate)>= g.datestart
GROUP BY g.name,g.Datestart
ORDER BY g.name,g.Datestart

i miss the criteria




Every rule in a world of bits and bytes, can be bend or eventually be broken
MyBlog About Common dialog control
A Visualizer for viewing SqlCommand object script
Post #1393321
« Prev Topic | Next Topic »

Add to briefcase 12»»

Permissions Expand / Collapse