Related
I have a string
04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO
I want output like
DateTime1 | EmpID
04/09/2018 06:21:38 101342
06/09/2018 08:41:38 101345
08/09/2018 09:41:38 10356
Please help
Create the function PatternSplitLoop from this awesome article:
Splitting Strings Based on Patterns
and execute the following:
declare #tab table (string varchar(max))
insert into #tab select '04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO '
select left(item, 19) DateTime1, substring(item, 20, len(item)) EmpID
from #tab t
cross apply [dbo].[PatternSplitLoop](string, '%[0-9][0-9][/][0-9][0-9][/][0-9][0-9][0-9][0-9]%') f
where matched = 1
Output:
XML split version:
DECLARE #Val NVARCHAR(MAX) = '04/09/2018 06:21:38 101342 CHARLESD JOHNSON:713-269-1878 CALL WHEN WE GET A PO 06/09/2018 08:41:38 101345 KHARLESD KOHNSON:813-269-1878 CALL WHEN WE GET A PO 08/09/2018 09:41:38 10356 THARLESD TOHNSON:913-269-1878 CALL WHEN WE GET A PO '
SELECT #Val = '<a>' + REPLACE(#Val, ' ', '</a><a>') + '</a>';
DECLARE #Xml XML = CONVERT(XML, #Val);
DECLARE #ValTable TABLE
(
ROWNUM INT IDENTITY(1, 1),
Val NVARCHAR(MAX)
)
INSERT into #ValTable
(Val)
SELECT *
FROM
(
SELECT c.value('.', 'NVARCHAR(64)') AS Val
FROM #Xml.nodes('/a') T(c)
) a
WHERE LEN(Val) <> 0
AND (TRY_CONVERT(DATETIME, Val) IS NOT NULL OR TRY_CONVERT(TIME, Val) IS NOT NULL OR TRY_CONVERT(INT, Val) IS NOT NULL);
SELECT CONVERT(DATETIME, CONCAT(a.Val, ' ', b.Val)) AS DateTime1, c.Val AS EmpId
FROM #ValTable a
JOIN #ValTable b
--Date and Time rows, B is time row
ON TRY_CONVERT(TIME, a.Val) IS NOT NULL AND TRY_CONVERT(TIME, b.Val) IS NOT NULL AND b.ROWNUM = a.ROWNUM + 1
-- Int rows
JOIN #ValTable c
ON TRY_CONVERT(INT, c.Val) IS NOT NULL AND c.ROWNUM = a.RowNum + 2;
I have T-SQL script that is parsing the MDX expression. It looks as:
IF OBJECT_ID ( 'tempdb..#metrics' ) IS NOT NULL
DROP TABLE #metrics
CREATE TABLE #metrics (
Metric VARCHAR(255)
)
---
DECLARE #counter INT = 1
DECLARE #mdx VARCHAR(4000) = 'SELECT {[Measures].[One],[Measures].[Two],[Measures].[Three],[Measures].[Four]} DIMENSION, PROPERTIES OTHER'
DECLARE #startString INT
DECLARE #endString INT
DECLARE #metric VARCHAR(200)
WHILE (1=1)
BEGIN
-- loop data and process them
SET #startString = (SELECT PATINDEX('%[[]Measures%',#mdx))
SET #endString = (SELECT CHARINDEX(',',#mdx))
SET #metric = (SELECT SUBSTRING(#mdx, #startString, #endString - #startString))
IF #metric LIKE '%}%'
BEGIN
SET #metric = LEFT(#metric, CHARINDEX('}',#metric) - 1)
INSERT INTO #metrics ( Metric ) SELECT #metric
SET #mdx = REPLACE(#mdx, #metric, '')
END
ELSE
BEGIN
INSERT INTO #metrics ( Metric ) SELECT #metric
SET #metric = #metric + ','
SET #mdx = REPLACE(#mdx, #metric, '')
END
-- break while
IF #mdx NOT LIKE '%[[]Measures%,%'
BEGIN
BREAK;
END
END
---
SELECT * FROM #metrics
Now, I need to apply this on more rows, but did not figure out how. I tried it with cursor, but it never ends. How to loop the logic on the following rows?
DECLARE #srcTable TABLE (
ID INT
,textData VARCHAR(4000)
)
INSERT INTO #srcTable ( ID, textData ) ( 1, 'SELECT {[Measures].[One],[Measures].[Two],[Measures].[Three],[Measures].[Four]} DIMENSION, PROPERTIES OTHER' )
,(2, 'SELECT {[Measures].[Five],[Measures].[Six],[Measures].[Seven]} DIMENSION, PROPERTIES OTHER' )
Desired Result:
1 [Measures].[One]
1 [Measures].[Two]
1 [Measures].[Three]
1 [Measures].[Four]
2 [Measures].[Five]
2 [Measures].[Six]
2 [Measures].[Seven]
DECLARE #t TABLE (
ID INT,
Metric VARCHAR(255)
)
INSERT INTO #t
VALUES
(1, 'SELECT {[Measures].[One],[Measures].[Two],[Measures].[Three],[Measures].[Four]} DIMENSION, PROPERTIES OTHER'),
(2, 'SELECT {[Measures].[Five],[Measures].[Six],[Measures].[Seven]} DIMENSION, PROPERTIES OTHER')
SELECT r.ID, item = t.c.value('.', 'VARCHAR(255)')
FROM (
SELECT *, txml = CAST('<r>' + REPLACE(Metric, ',', '</r><r>') + '</r>' AS XML)
FROM (
SELECT ID, Metric = SUBSTRING(Metric, CHARINDEX('{',Metric) + 1, CHARINDEX('}',Metric) - CHARINDEX('{',Metric) - 1)
FROM #t
) t
) r
CROSS APPLY txml.nodes('/r') t(c)
Output -
ID item
----------- -----------------------
1 [Measures].[One]
1 [Measures].[Two]
1 [Measures].[Three]
1 [Measures].[Four]
2 [Measures].[Five]
2 [Measures].[Six]
2 [Measures].[Seven]
I want to summarize a table that is mostly made up of a sequence of months. Each month's column has a header in the format of MMMYY. I need to dynamically summarize this table by fiscal year. Our fiscal year starts in November, so the input to output would be as follows:
Input:
Output:
Does anyone have any suggestions on how I can go about doing this using SQL Server? I've thought about partitioning a temporary table containing all of the given months and years by the monthly fiscal year break (NovYY), but I haven't figured out how to even partition based on a LIKE keyword search. Bottom line - I'm completely stumped as to how to effectively do this without hard coding the dates.
Let's say the sample input above is dbo.USA_Historic_Txg_Revenue. I have the following so far:
select * into #temp from dbo.USA_Historic_Txg_Revenue
with MMMYY as
(
select Name
from tempdb.sys.columns
where object_id = OBJECT_ID('tempdb..#temp')
and isnumeric(right(name, 2)) = 1
)
select * from MMMYY
Something like this is what I think you're looking for:
--CREATE TABLE #table (Name NVARCHAR(100), Oct12 INT, Nov12 INT, Dec12 INT, Jan13 INT, Feb13 INT, Mar13 INT, Apr13 INT, May13 INT, Jun13 INT, Jul13 INT, Aug13 INT, Sep13 INT, Oct13 INT, Nov13 INT, Dec13 INT, Jan14 INT, Feb14 INT, Mar14 INT)
--INSERT #table VALUES ('Record1',5,3,2,0,1,5,4,3,6,5,4,2,1,0,1,1,1,2)
--, ('Record2',4,1,3,2,1,3,3,1,4,4,3,2,1,0,2,2,2,2);
DECLARE #monthlist NVARCHAR(MAX)
SELECT #monthlist = ISNULL(#monthlist + ',', '') + Name -- select top 100 *
FROM tempdb.sys.columns
WHERE [object_id] = OBJECT_ID('tempdb..#table')
AND Name <> 'Name';
DECLARE #SQL NVARCHAR(MAX) =
'SELECT DISTINCT Name
, SUM(Val) OVER (PARTITION BY Name, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN RIGHT(Mth, 2) ELSE RIGHT(Mth, 2) - 1 END) InsertColName
, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN ''Nov'' + RIGHT(Mth, 2) ELSE ''Nov'' + CONVERT(NVARCHAR, RIGHT(Mth, 2) - 1) END FiscalStart
FROM #table
UNPIVOT (Val FOR Mth IN (' + #monthlist + ')) a
ORDER BY Name, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN ''Nov'' + RIGHT(Mth, 2) ELSE ''Nov'' + CONVERT(NVARCHAR, RIGHT(Mth, 2) - 1) END'
EXEC(#SQL)
For your particular query, you can derive monthlist directly from the table without the need of a temporary table...
e.g.
DECLARE #monthlist NVARCHAR(MAX)
SELECT #monthlist = ISNULL(#monthlist + ',', '') + COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'USA_Historic_Txg_Revenue'
AND COLUMN_NAME <> 'Name';
DECLARE #SQL NVARCHAR(MAX) =
'SELECT DISTINCT Name
, SUM(Val) OVER (PARTITION BY Name, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN RIGHT(Mth, 2) ELSE RIGHT(Mth, 2) - 1 END) InsertColName
, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN ''Nov'' + RIGHT(Mth, 2) ELSE ''Nov'' + CONVERT(NVARCHAR, RIGHT(Mth, 2) - 1) END FiscalStart
FROM dbo.USA_Historic_Txg_Revenue
UNPIVOT (Val FOR Mth IN (' + #monthlist + ')) a
ORDER BY Name, CASE WHEN Mth LIKE ''Nov%'' OR Mth LIKE ''Dec%'' THEN ''Nov'' + RIGHT(Mth, 2) ELSE ''Nov'' + CONVERT(NVARCHAR, RIGHT(Mth, 2) - 1) END'
EXEC(#SQL)
[Summarizing months columns using pivot][1]
---creating the tables
CREATE TABLE [dbo].[Table1]([PID] [int] NULL,[ProductDesc] [nvarchar](50) NULL,[ProductCode] [nvarchar](10) NULL) ON [PRIMARY]
CREATE TABLE [dbo].[Table2]([Date] [varchar](50) NULL,[PID] [int] NULL) ON [PRIMARY]
---insert script---
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode]) VALUES (1, N'Packet-Eye', N'P001')
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode]) VALUES (2, N'Wiggy', N'W099 ')
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode]) VALUES (3, N'Wimax-Lite', N'W001')
INSERT [dbo].[Table1] ([PID], [ProductDesc], [ProductCode]) VALUES (4, N'Wimax-Home', N'e W002 ')
INSERT [dbo].[Table2] ([Date], [PID]) VALUES (N'1/14/2009 ', 1)
INSERT [dbo].[Table2] ([Date], [PID]) VALUES (N'1/15/2009 ', 1)
INSERT [dbo].[Table2] ([Date], [PID]) VALUES (N'2/1/2009', 2)
INSERT [dbo].[Table2] ([Date], [PID]) VALUES (N'3/3/2009', 3)
GO
SELECT *
FROM
(
SELECT t1.productdesc as pd,COUNT(month(t2.date))as dates,
DateName( month , DateAdd( month , MONTH(t2.date) , 0 ) - 1 ) as mon
FROM table1 t1 inner join table2 t2 on t1.pid=t2.pid
where year(date) between 2009
and 2010 group by productdesc,month(t2.date),month (t2.date)
) AS D
PIVOT
(
sum(dates)
FOR mon IN( [January],[February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December])
) AS P
[using pivot in sqlserver please find the result in the below image][1]
[1]: http://i.stack.imgur.com/jio6c.png
Have table :
id name
1 A1=7|A5=1|A10=5|A20=12|A50=8
2 A1=10|A5=2|A10=10|A20=14|A50=4
3 A1=3|A5=3|A10=5|A20=12|A50=8
.
.
Want sum all A1,A5,A10,A20,A50
Response must be like :
A1=20|A5=6|A10=20|A20=38|A50=20
How to do it ?
I also upvoted comment about changing table design but there are situations when somebody cannot do this. So here is the solution for this case and it's not so difficult. We call XML for assistance as usual when need to process formatted strings in XML columns.
-- Prepare data for solution testing
DECLARE #srctable TABLE (
id INT,
name VARCHAR(999),
namexml XML
)
INSERT INTO #srctable
SELECT id, name, namexml FROM ( VALUES
(1, 'A1=7|A5=1|A10=5|A20=12|A50=8', null),
(2, 'A1=10|A5=2|A10=10|A20=14|A50=4', null),
(3, 'A1=3|A5=3|A10=5|A20=12|A50=8', null)
) v (id, name, namexml)
-- Transform source formatted string to XML string
UPDATE #srctable
SET namexml = CAST('<row><data ' + REPLACE(REPLACE(name, '|', '"/><data '), '=', '="') + '"/></row>' AS XML)
-- Final select from XML data
SELECT SUM(x.data.value('(#A1)[1]', 'INT')) AS SUMA1,
SUM(x.data.value('(#A5)[1]', 'INT')) AS SUMA5,
SUM(x.data.value('(#A10)[1]', 'INT')) AS SUMA10,
SUM(x.data.value('(#A20)[1]', 'INT')) AS SUMA20,
SUM(x.data.value('(#A50)[1]', 'INT')) AS SUMA50
FROM #srctable AS t
CROSS APPLY t.namexml.nodes('/row/data') x (data)
You need to format your resulting string in any way you wish.
Variant without xml:
--------------------------------------------------------------------------------
-- Prepare data for solution testing
DECLARE #srctable TABLE ( id INT
, NAME VARCHAR(999) )
INSERT INTO #srctable
VALUES ( 1, 'A1=7|A5=1|A10=5|A20=12|A50=8' )
, ( 2, 'A1=10|A5=2|A10=10|A20=14|A50=4' )
, ( 3, 'A1=3|A5=3|A10=5|A20=12|A50=8' )
--------------------------------------------------------------------------------
-- prepare temp table for using in split string
DECLARE #Tally TABLE ( N INT )
DECLARE #i AS INT = 1
WHILE #i != 1000
BEGIN
INSERT INTO #Tally ( N )
VALUES ( #i )
SET #i = #i + 1
END
--------------------------------------------------------------------------------
--final query
;WITH cte AS
(
SELECT id,
(CASE WHEN CHARINDEX('|', S.string) > 0
THEN left(S.string, CHARINDEX('|', S.string) - 1)
ELSE string END ) NAME
FROM #srctable AS E
INNER JOIN #Tally AS T ON SUBSTRING('|' + NAME, T.N, 1) = '|'
AND T.N <= LEN(NAME)
CROSS APPLY (SELECT String = (CASE WHEN T.N = 1
THEN LEFT(E.NAME, CHARINDEX('|', E.NAME) - 1)
ELSE SUBSTRING(E.NAME, T.N, 1000) END )
) AS S
)
SELECT LEFT(NAME, CHARINDEX('=', NAME) - 1) AS NAME,
SUM(convert(float,RIGHT(NAME, CHARINDEX('=', REVERSE(NAME)) - 1))) AS Value
FROM cte
GROUP BY LEFT(NAME, CHARINDEX('=', NAME) - 1)
I am trying to use a recursive CTE in SQL Server to build up a predicate formula from a table containing the underlying tree structure.
For example, my table looks like:
Id | Operator/Val | ParentId
--------------------------
1 | 'OR' | NULL
2 | 'AND' | 1
3 | 'AND' | 1
4 | '>' | 2
5 | 'a' | 4
6 | 'alpha' | 4
...
...which represents ((a > alpha) AND (b > beta)) OR ((c > gamma) AND (a < delta)).
ParentId is a reference to the Id in the same table of the parent node.
I want to write a query which will build up this string from the table. Is it possible?
Thanks
For a production environment, you may want to go with a recursive function for simplicity if performance and recursion depth limits (32 levels) is not a problem.
However, here's a quite clean and pretty efficient solution with CTEs (note that it will accept any number of "trees" and return one result for each item which has no parent):
DECLARE #tbl TABLE
(
id int PRIMARY KEY
NOT NULL,
op nvarchar(max) NOT NULL,
parent int
) ;
INSERT INTO #tbl
SELECT 1, 'OR', NULL UNION ALL
SELECT 2, 'AND', 1 UNION ALL
SELECT 3, 'AND', 1 UNION ALL
SELECT 4, '>', 2 UNION ALL
SELECT 5, 'a', 4 UNION ALL
SELECT 6, 'alpha', 4 UNION ALL
SELECT 7, '>', 2 UNION ALL
SELECT 8, 'b', 7 UNION ALL
SELECT 9, 'beta', 7 UNION ALL
SELECT 10, '>', 3 UNION ALL
SELECT 11, 'c', 10 UNION ALL
SELECT 12, 'gamma', 10 UNION ALL
SELECT 13, '>', 3 UNION ALL
SELECT 14, 'd', 13 UNION ALL
SELECT 15, 'delta', 13 ;
WITH nodes -- A CTE which sets a flag to 1 for non-leaf nodes
AS (
SELECT t.*, CASE WHEN p.parent IS NULL THEN 0
ELSE 1
END node
FROM #tbl t
LEFT JOIN (
SELECT DISTINCT parent
FROM #tbl
) p ON p.parent = T.id
),
rec -- the main recursive run to determine the sort order and add meta information
AS (
SELECT id rootId, node lvl, CAST(0 AS float) sort, CAST(0.5 AS float) offset, *
FROM nodes
WHERE parent IS NULL
UNION ALL
SELECT r.rootId, r.lvl+t.node, r.sort+r.offset*CAST((ROW_NUMBER() OVER (ORDER BY t.id)-1)*2-1 AS float),
r.offset/2, t.*
FROM rec r
JOIN
nodes t ON r.id = t.parent
),
ranked -- ranking of the result to sort and find the last item
AS (
SELECT rootId, ROW_NUMBER() OVER (PARTITION BY rootId ORDER BY sort) ix,
COUNT(1) OVER (PARTITION BY rootId) cnt, lvl, op
FROM rec
),
concatenated -- concatenate the string, adding ( and ) as needed
AS (
SELECT rootId, ix, cnt, lvl, CAST(REPLICATE('(', lvl)+op AS nvarchar(max)) txt
FROM ranked
WHERE ix = 1
UNION ALL
SELECT r.rootId, r.ix, r.cnt, r.lvl,
c.txt+COALESCE(REPLICATE(')', c.lvl-r.lvl), '')+' '+COALESCE(REPLICATE('(', r.lvl-c.lvl), '')+r.op
+CASE WHEN r.ix = r.cnt THEN REPLICATE(')', r.lvl)
ELSE ''
END
FROM ranked r
JOIN
concatenated c ON (r.rootId = c.rootId)
AND (r.ix = c.ix+1)
)
SELECT rootId id, txt
FROM concatenated
WHERE ix = cnt
OPTION (MAXRECURSION 0);
I found something, but it looks pretty nasty. You would be able to do this a lot easier using a recursive fundtion...
DECLARE #Table TABLE(
ID INT,
Op VARCHAR(20),
ParentID INT
)
INSERT INTO #Table SELECT 1,'OR',NULL
INSERT INTO #Table SELECT 2,'AND',1
INSERT INTO #Table SELECT 3,'AND',1
INSERT INTO #Table SELECT 4,'>',2
INSERT INTO #Table SELECT 5,'a',4
INSERT INTO #Table SELECT 6,'alpha',4
INSERT INTO #Table SELECT 7,'>',2
INSERT INTO #Table SELECT 8,'b',7
INSERT INTO #Table SELECT 9,'beta',7
INSERT INTO #Table SELECT 10,'>',3
INSERT INTO #Table SELECT 11,'c',10
INSERT INTO #Table SELECT 12,'gamma',10
INSERT INTO #Table SELECT 13,'<',3
INSERT INTO #Table SELECT 14,'a',13
INSERT INTO #Table SELECT 15,'delta',13
;WITH Vals AS (
SELECT t.*,
1 Depth
FROM #Table t LEFT JOIN
#Table parent ON t.ID = parent.ParentID
WHERE parent.ParentID IS NULL
UNION ALL
SELECT t.*,
v.Depth + 1
FROM #Table t INNER JOIN
Vals v ON v.ParentID = t.ID
),
ValLR AS(
SELECT DISTINCT
vLeft.ID LeftID,
vLeft.Op LeftOp,
vRight.ID RightID,
vRight.Op RightOp,
vLeft.ParentID OperationID,
vLeft.Depth
FROM Vals vLeft INNER JOIN
Vals vRight ON vLeft.ParentID = vRight.ParentID
AND vLeft.ID < vRight.ID
WHERE (vRight.ID IS NOT NULL)
),
ConcatVals AS(
SELECT CAST('(' + LeftOp + ' ' + Op + ' ' + RightOp + ')' AS VARCHAR(500)) ConcatOp,
t.ID OpID,
v.Depth,
1 CurrentDepth
FROM ValLR v INNER JOIN
#Table t ON v.OperationID = t.ID
WHERE v.Depth = 1
UNION ALL
SELECT CAST('(' + cL.ConcatOp + ' ' + t.Op + ' {' + CAST(v.RightID AS VARCHAR(10)) + '})' AS VARCHAR(500)) ConcatOp,
t.ID OpID,
v.Depth,
cL.CurrentDepth + 1
FROM ValLR v INNER JOIN
#Table t ON v.OperationID = t.ID INNER JOIN
ConcatVals cL ON v.LeftID = cL.OpID
WHERE v.Depth = cL.CurrentDepth + 1
),
Replaces AS(
SELECT REPLACE(
c.ConcatOp,
SUBSTRING(c.ConcatOp,PATINDEX('%{%', c.ConcatOp), PATINDEX('%}%', c.ConcatOp) - PATINDEX('%{%', c.ConcatOp) + 1),
(SELECT ConcatOp FROM ConcatVals WHERE OpID = CAST(SUBSTRING(c.ConcatOp,PATINDEX('%{%', c.ConcatOp) + 1, PATINDEX('%}%', c.ConcatOp) - PATINDEX('%{%', c.ConcatOp) - 1) AS INT))
) ConcatOp,
1 Num
FROM ConcatVals c
WHERE Depth = (SELECT MAX(Depth) FROM ConcatVals)
UNION ALL
SELECT REPLACE(
r.ConcatOp,
SUBSTRING(r.ConcatOp,PATINDEX('%{%', r.ConcatOp), PATINDEX('%}%', r.ConcatOp) - PATINDEX('%{%', r.ConcatOp) + 1),
(SELECT ConcatOp FROM ConcatVals WHERE OpID = CAST(SUBSTRING(r.ConcatOp,PATINDEX('%{%', r.ConcatOp) + 1, PATINDEX('%}%', r.ConcatOp) - PATINDEX('%{%', r.ConcatOp) - 1) AS INT))
) ConcatOp,
Num + 1
FROM Replaces r
WHERE PATINDEX('%{%', r.ConcatOp) > 0
)
SELECT TOP 1
*
FROM Replaces
ORDER BY Num DESC
OUTPUT
ConcatOp
----------------------------------------------------------------
(((a > alpha) AND (b > beta)) OR ((c > gamma) AND (a < delta)))
If you would rather want to look at a recursive function, give me a shout and we can have a look.
EDIT: Recursive Function
Have a look at how much easier this is
CREATE TABLE TableValues (
ID INT,
Op VARCHAR(20),
ParentID INT
)
INSERT INTO TableValues SELECT 1,'OR',NULL
INSERT INTO TableValues SELECT 2,'AND',1
INSERT INTO TableValues SELECT 3,'AND',1
INSERT INTO TableValues SELECT 4,'>',2
INSERT INTO TableValues SELECT 5,'a',4
INSERT INTO TableValues SELECT 6,'alpha',4
INSERT INTO TableValues SELECT 7,'>',2
INSERT INTO TableValues SELECT 8,'b',7
INSERT INTO TableValues SELECT 9,'beta',7
INSERT INTO TableValues SELECT 10,'>',3
INSERT INTO TableValues SELECT 11,'c',10
INSERT INTO TableValues SELECT 12,'gamma',10
INSERT INTO TableValues SELECT 13,'<',3
INSERT INTO TableValues SELECT 14,'a',13
INSERT INTO TableValues SELECT 15,'delta',13
GO
CREATE FUNCTION ReturnMathVals (#ParentID INT, #Side VARCHAR(1))
RETURNS VARCHAR(500)
AS
BEGIN
DECLARE #RetVal VARCHAR(500)
IF (#ParentID IS NULL)
BEGIN
SELECT #RetVal = ' (' + dbo.ReturnMathVals(ID,'L') + Op + dbo.ReturnMathVals(ID,'R') + ') '
FROM TableValues
WHERE ParentID IS NULL
END
ELSE
BEGIN
SELECT TOP 1 #RetVal = ' (' + dbo.ReturnMathVals(ID,'L') + Op + dbo.ReturnMathVals(ID,'R') + ') '
FROM TableValues
WHERE ParentID = #ParentID
ORDER BY CASE WHEN #Side = 'L' THEN ID ELSE -ID END
SET #RetVal = ISNULL(#RetVal, (SELECT TOP 1 Op FROM TableValues WHERE ParentID = #ParentID ORDER BY CASE WHEN #Side = 'L' THEN ID ELSE -ID END))
END
RETURN #RetVal
END
GO
SELECT dbo.ReturnMathVals(NULL, NULL)
GO
DROP FUNCTION ReturnMathVals
DROP TABLE TableValues
Yes it is possible to do it but the problem is not the CTE, check it with PIVOT
read more about it from this link
http://msdn.microsoft.com/en-us/library/ms177410.aspx
some examples in this documentation is similar with your problem
I couldn't figure out how to do the double-recursion, but hopefully one of the intermediate CTEs in this will set you on the right track:
SET NOCOUNT ON
DECLARE #tree AS TABLE
(
Id int NOT NULL
,Operator varchar(10) NOT NULL
,ParentId int
)
INSERT INTO #tree
VALUES (1, 'OR', NULL)
INSERT INTO #tree
VALUES (2, 'AND', 1)
INSERT INTO #tree
VALUES (3, 'AND', 1)
INSERT INTO #tree
VALUES (4, '>', 2)
INSERT INTO #tree
VALUES (5, 'a', 4)
INSERT INTO #tree
VALUES (6, 'alpha', 4)
INSERT INTO #tree
VALUES (7, '>', 2)
INSERT INTO #tree
VALUES (8, 'b', 7)
INSERT INTO #tree
VALUES (9, 'beta', 7)
INSERT INTO #tree
VALUES (10, '>', 3)
INSERT INTO #tree
VALUES (11, 'c', 10)
INSERT INTO #tree
VALUES (12, 'gamma', 10)
INSERT INTO #tree
VALUES (13, '>', 3)
INSERT INTO #tree
VALUES (14, 'd', 13)
INSERT INTO #tree
VALUES (15, 'delta', 13) ;
WITH lhs_selector
AS (
SELECT ParentId
,MIN(Id) AS Id
FROM #tree
GROUP BY ParentId
),
rhs_selector
AS (
SELECT ParentId
,MAX(Id) AS Id
FROM #tree
GROUP BY ParentId
),
leaf_selector
AS (
SELECT Id
FROM #tree AS leaf
WHERE NOT EXISTS ( SELECT *
FROM #tree
WHERE ParentId = leaf.Id )
),
recurse
AS (
SELECT operator.Id
,CASE WHEN lhs_is_leaf.Id IS NOT NULL THEN NULL
ELSE lhs.Id
END AS LhsId
,CASE WHEN rhs_is_leaf.Id IS NOT NULL THEN NULL
ELSE rhs.Id
END AS RhsId
,CASE WHEN COALESCE(lhs_is_leaf.Id, rhs_is_leaf.Id) IS NULL
THEN '({' + CAST(lhs.Id AS varchar) + '} ' + operator.Operator + ' {'
+ CAST(rhs.Id AS varchar) + '})'
ELSE '(' + lhs.Operator + ' ' + operator.Operator + ' ' + rhs.Operator + ')'
END AS expression
FROM #tree AS operator
INNER JOIN lhs_selector
ON lhs_selector.ParentID = operator.Id
INNER JOIN rhs_selector
ON rhs_selector.ParentID = operator.Id
INNER JOIN #tree AS lhs
ON lhs.Id = lhs_selector.Id
INNER JOIN #tree AS rhs
ON rhs.Id = rhs_selector.Id
LEFT JOIN leaf_selector AS lhs_is_leaf
ON lhs_is_leaf.Id = lhs.Id
LEFT JOIN leaf_selector AS rhs_is_leaf
ON rhs_is_leaf.Id = rhs.Id
)
SELECT *
,REPLACE(REPLACE(op.expression, '{' + CAST(op.LhsId AS varchar) + '}', lhs.expression),
'{' + CAST(op.RhsId AS varchar) + '}', rhs.expression) AS final_expression
FROM recurse AS op
LEFT JOIN recurse AS lhs
ON lhs.Id = op.LhsId
LEFT JOIN recurse AS rhs
ON rhs.Id = op.RhsId