SQL: Order by substring of mixed letters and numbers - sql

How might I select the following data in an existing table and order by a mix of letters and numbers. Here is the sample...
A-1
A-10
A-2
A-3
A-4
A-5
A-6
A-7
A-8
A-9
A-3a
A-3b
A-3c
B-1
B-10
B-11
B-12
B-12a
B-12b
B-13
B-2
B-3
B-4
B-5
B-6
B-7
B-8
B-9

I place this as a new answer, as it is not really an answer but rather a comparison of different approaches:
The conclusio:
all approaches scale fairly linear, except XML
XML is fastest with small row count but gets worse with high row count
Create a test scenario
CREATE TABLE #tbl (ID INT IDENTITY,sortColumn VARCHAR(100));
INSERT INTO #tbl VALUES
('A-1')
,('A-10')
,('A-2')
,('A-3')
,('A-4')
,('A-5')
,('A-6')
,('A-7')
,('A-8')
,('A-9')
,('A-3a')
,('A-3b')
,('A-3c')
,('B-1')
,('B-10')
,('B-11')
,('B-12')
,('B-12a')
,('B-12b')
,('B-13')
,('B-2')
,('B-3')
,('B-4')
,('B-5')
,('B-6')
,('B-7')
,('B-8')
,('A-8a')
,('B-8')
,('B-9'); --30 rows
GO 1000 -- x 1.000 = 30.000 rows
Matt's approach (cleaned to the necessary)
46 seconds on 3 mio rows
4.5 seconds on 300.000 rows
1.3 seconds on 30.000 rows
0.7 seconds on 3.000 rows
The code
SELECT ID,sortColumn
FROM
#tbl
ORDER BY
LEFT(sortColumn,CHARINDEX('-',sortColumn) -1)
,CAST((CASE
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,3)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,3)
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,2)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,2)
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,1)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,1)
ELSE NULL
END) AS INT)
,RIGHT(sortColumn,
LEN(sortColumn) -
LEN(LEFT(sortColumn,CHARINDEX('-',sortColumn) -1))
- LEN(CASE
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,3)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,3)
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,2)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,2)
WHEN ISNUMERIC(SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,1)) = 1 THEN SUBSTRING(sortColumn,CHARINDEX('-',sortColumn) + 1,1)
ELSE NULL
END)
- 1 --the '-'
),ID;
Stepwise calculation in CROSS APPLYs, sorting on calculated columns
44 seconds on 3 mio rows
4.4 seconds on 300.000 rows
0.9 seconds on 30.000 rows
0.3 seconds on 3.000 rows
The code
SELECT ID,sortColumn
FROM #tbl
CROSS APPLY(SELECT CHARINDEX('-',sortColumn) AS posMinus) AS pos
CROSS APPLY(SELECT SUBSTRING(sortColumn,1,posMinus-1) AS part1
,SUBSTRING(sortColumn,posMinus+1,1000) AS part2
) AS parts
CROSS APPLY(SELECT ISNUMERIC(part2) AS p2isnum) AS checknum
CROSS APPLY(SELECT CASE WHEN p2isnum=1 THEN '' ELSE RIGHT(part2,1) END AS part3
,CASE WHEN p2isnum=1 THEN part2 ELSE SUBSTRING(part2,1,LEN(part2)-1) END AS part2New
) AS partsNew
ORDER BY part1,part2new,part3,ID;
Stepwise calculation in CROSS APPLYs, sorting on concatenated padded string
42 seconds on 3 mio rows
4.2 seconds on 300.000 rows
0.7 seconds on 30.000 rows
0.4 seconds on 3.000 rows
The code
SELECT ID,sortColumn
FROM #tbl
CROSS APPLY(SELECT CHARINDEX('-',sortColumn) AS posMinus) AS pos
CROSS APPLY(SELECT SUBSTRING(sortColumn,1,posMinus-1) AS part1
,SUBSTRING(sortColumn,posMinus+1,1000) AS part2
) AS parts
ORDER BY RIGHT('.....' + part1,5) + RIGHT('.....' + part2,5 - ISNUMERIC(RIGHT(part2,1)))
,ID;
Splitting with XML, sorting on concatenated padded string
67 seconds on 3 mio rows
6.2 seconds on 300.000 rows
0.7 seconds on 30.000 rows
0.3 seconds on 3.000 rows
The code
SELECT ID,sortColumn
FROM
(
SELECT CAST('<r>' + REPLACE(sortColumn,'-','</r><r>') + '</r>' AS XML) AS SortColumnSplitted
,*
FROM #tbl
) AS tbl
ORDER BY RIGHT('.....' + SortColumnSplitted.value('r[1]','varchar(max)'),5) + RIGHT('.....' + SortColumnSplitted.value('r[2]','varchar(max)'),5 - ISNUMERIC(RIGHT(SortColumnSplitted.value('r[2]','varchar(max)'),1)))
,ID;

I agree with thomas, but I also have a lot of the .Net Regex and String functions exposed via CLR. Other techniques we use a little are user defined functions that recursively go character by character to strip out non desired characters (e.g. no alpha when looking for a number, no number when looking for alpha). But in the particular case you presented if you know the format will be pretty standard you can use a combination of ISNUMERIC, SUBSTRINGS, etc. to reach your goal pretty easily. For example. If you know it is always:
Alpha + "-" + Numeric (1-3 digits) + alpha
you could do the following and it will sort The alpha as alpha, numeric as numeric, and alpha as alpha.
DECLARE #Values AS TABLE (Value VARCHAR(5))
INSERT INTO #Values (Value)
VALUES ('A-1')
,('A-10')
,('A-2')
,('A-3')
,('A-4')
,('A-5')
,('A-6')
,('A-7')
,('A-8')
,('A-9')
,('A-3a')
,('A-3b')
,('A-3c')
,('B-1')
,('B-10')
,('B-11')
,('B-12')
,('B-12a')
,('B-12b')
,('B-13')
,('B-2')
,('B-3')
,('B-4')
,('B-5')
,('B-6')
,('B-7')
,('B-8')
,('B-9')
SELECT
*
,FirstAlphaSection = LEFT(Value,CHARINDEX('-',Value) -1)
,SecondNumericSection = CASE
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)
ELSE NULL
END
,ThirdAlphaSection =
RIGHT(Value,
LEN(Value) -
LEN(LEFT(Value,CHARINDEX('-',Value) -1))
- LEN(CASE
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)
ELSE NULL
END)
- 1 --the '-'
)
FROM
#Values
ORDER BY
LEFT(Value,CHARINDEX('-',Value) -1)
,CAST((CASE
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)
ELSE NULL
END) AS INT)
,RIGHT(Value,
LEN(Value) -
LEN(LEFT(Value,CHARINDEX('-',Value) -1))
- LEN(CASE
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,3)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,2)
WHEN ISNUMERIC(SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)) = 1 THEN SUBSTRING(Value,CHARINDEX('-',Value) + 1,1)
ELSE NULL
END)
- 1 --the '-'
)

The most powerful solution is to create an SQL CLR function. That's a bit tough, though.
Another approach is writing an insert/update trigger that splits the value in the mixed column with TSQL and stores the three parts (character, number, character) in specific helper columns (that you can use to sort).
Based on your examples, you can experiment with the splitting along the lines of this code:
declare #value nvarchar(10) = 'B-12b';
-- first part
select substring(#value, 1, 1)
-- second part
select case when isnumeric(right(#value, 1)) = 1
then substring(#value, 3, len(#value) - 2)
else substring(#value, 3, len(#value) - 3)
end
-- third part
select case when isnumeric(right(#value, 1)) = 1
then '_'
else right(#value, 1)
end

Related

List combination of numbers which have same sum

**N** is a prositive number
Need list of scenarios which have sum equal N
For example if N=4
ScenarioId Value
---------- -----
1 1
1 1
1 1
1 1
2 2
2 1
2 1
3 2
3 2
4 3
4 1
5 4
above list is required. If you sum by ScenarioId all sum must equal to N
UPDATE
Here is my own solution. however, I am not sure about the multiplication of two different number sets would not be equal at any time.
My current question is
Is there any possibilities a + b + c = d + e + f and a * b * c = d * e * f
Test link is here
DECLARE #N int = 4;
SELECT
[Value] = CAST(number + 1 as tinyint)
INTO #Values
FROM master.dbo.spt_values
WHERE number < #N
AND [Type] = 'p'
;WITH COMBINATIONS AS(
SELECT ScenarioKey = CAST(NULL AS nvarchar(MAX)), [Value], Total = 0, Multipication = 1, MemeberCount = 0
FROM #Values
UNION ALL
SELECT ScenarioKey = ISNULL(S.ScenarioKey, '') + IIF(S.ScenarioKey IS NULL, '', N'-') + CAST(P.[Value] AS nvarchar(10)), S.[Value], Total = S.Total + P.[Value], Multipication = S.Multipication * P.[Value], MemeberCount = MemeberCount + 1
FROM #Values P
JOIN COMBINATIONS AS S ON S.Total < S.[Value]
),
SCENARIOS AS(
SELECT
ScenarioKey
,ScenarioId = ROW_NUMBER() OVER(ORDER BY ScenarioKey)
,[Value]
FROM
(
SELECT
ScenarioKey
,[Value]
,Multipication
,MemeberCount
-- this will prevent dublications. because 1 * 2 * 3 = 3 * 2 * 1
-- however, I am not sure about multipication of two different number sets would not be equal any time
,RowNo = ROW_NUMBER() OVER(PARTITION BY [Value],Multipication,MemeberCount ORDER BY [Value],ScenarioKey)
FROM COMBINATIONS
WHERE Total = #N
) X
WHERE RowNo = 1 AND [Value] = #N
)
SELECT
R.ScenarioId
,[Value] = S.[value]
FROM SCENARIOS R
CROSS APPLY (SELECT [value] FROM STRING_SPLIT(R.ScenarioKey, '-')) S
DROP TABLE #Values
It's too long for comment, so I post this as an answer. I want to note, that this is a static example, but I hope it can be easily translated as a dynamic statement.
Steps are written as comments in the statement:
WITH rcte AS
(
-- Recursive query to generate all numbers from 1 to 4
SELECT 0 AS Number
UNION ALL
SELECT Number + 1
FROM rcte
WHERE Number < 4
), permutations AS (
-- All possible permutations with sum equal to 4
-- There is additional column DuplicateMarker.
-- It will be used later, because 0,0,0,4 and 0,4,0,0 are the same
SELECT
t1.Number AS Number1,
t2.Number AS Number2,
t3.Number AS Number3,
t4.Number AS Number4,
CONCAT(LTRIM(STR(t1.Number)), '.', LTRIM(STR(t2.Number)), '.', LTRIM(STR(t3.Number)), '.', LTRIM(STR(t4.Number))) AS DuplicateMarker
FROM rcte t1, rcte t2, rcte t3, rcte t4
WHERE (t1.Number + t2.Number + t3.Number + t4.Number) = 4
), duplicates AS (
-- Get data with splitted DuplicateMarker column
SELECT *
FROM permutations
CROSS APPLY (SELECT [value] FROM STRING_SPLIT(DuplicateMarker, '.')) t
), results AS (
-- Get unique combinations
-- WITHIN GROUP (ORDER BY) will order strings and 0.0.0.4 and 0.4.0.0 will be the same
SELECT DISTINCT STRING_AGG([value], '.') WITHIN GROUP (ORDER BY [value]) AS ScenarioValue
FROM duplicates
GROUP BY Number1, Number2, Number3, Number4
)
SELECT
DENSE_RANK() OVER (ORDER BY r.ScenarioValue) AS ScenarioID,
s.[value]
FROM results r
CROSS APPLY (SELECT [value] FROM STRING_SPLIT(r.ScenarioValue, '.')) s
WHERE [value] <> '0'
Output:
ScenarioID value
1 4
2 1
2 3
3 2
3 2
4 1
4 1
4 2
5 1
5 1
5 1
5 1
Update:
Thanks to #AndriyM's comment, I've made some changes and now you can eliminate string manipulations:
WITH rcte AS
(
-- Recursive query to generate all numbers from 0 to 4
SELECT 0 AS Number
UNION ALL
SELECT Number + 1
FROM rcte
WHERE Number < 4
), combinations AS (
-- All different combinations with sum equal to 4
SELECT
t1.Number AS Number1,
t2.Number AS Number2,
t3.Number AS Number3,
t4.Number AS Number4,
ROW_NUMBER() OVER (ORDER BY t1.Number, t2.Number, t3.Number, t4.NUmber) AS ScenarioID
FROM rcte t1, rcte t2, rcte t3, rcte t4
WHERE
((t1.Number + t2.Number + t3.Number + t4.Number) = 4) AND
(t1.Number <= t2.Number) AND
(t2.Number <= t3.Number) AND
(t3.Number <= t4.Number)
)
SELECT c.ScenarioID, v.[value]
FROM combinations c
CROSS APPLY (VALUES (c.NUmber1), (c.Number2), (c.Number3), (c.Number4)) AS v ([value])
WHERE v.[value] > 0
Update 2:
Approach using dynamic statement - probably not the best approach, but is based on statement from first update:
-- Set your #n value
DECLARE #n int
SET #n = 4
-- Declarations
DECLARE #combinationsSelect nvarchar(max)
DECLARE #combinationsRowNumber nvarchar(max)
DECLARE #combinationsFrom nvarchar(max)
DECLARE #combinationsWhere1 nvarchar(max)
DECLARE #combinationsWhere2 nvarchar(max)
DECLARE #combinationsValues nvarchar(max)
SET #combinationsSelect = N''
SET #combinationsRowNumber = N''
SET #combinationsFrom = N''
SET #combinationsValues = N''
SET #combinationsWhere1 = N''
SET #combinationsWhere2 = N''
-- Generate dynamic parts of the statement
;WITH numbers AS
(
SELECT 1 AS Number
UNION ALL
SELECT Number + 1
FROM Numbers
WHERE Number < #n
)
SELECT
#combinationsSelect = #combinationsSelect + N', t' + LTRIM(STR(Number)) + N'.Number AS Number' + LTRIM(STR(Number)),
#combinationsRowNumber = #combinationsRowNumber + N', t' + LTRIM(STR(Number)) + N'.Number',
#combinationsValues = #combinationsValues + N', (c.Number' + LTRIM(STR(Number)) + N')',
#combinationsFrom = #combinationsFrom + N', rcte t' + LTRIM(STR(Number)),
#combinationsWhere1 = #combinationsWhere1 + N'+ t' + LTRIM(STR(Number)) + N'.Number ',
#combinationsWhere2 = #combinationsWhere2 +
CASE
WHEN Number = 1 THEN N''
ELSE N'AND (t' + LTRIM(STR(Number-1)) + N'.Number <= t' + + LTRIM(STR(Number)) + N'.Number) '
END
FROM
numbers
SET #combinationsSelect = STUFF(#combinationsSelect, 1, 2, N'')
SET #combinationsRowNumber = STUFF(#combinationsRowNumber, 1, 2, N'')
SET #combinationsValues = STUFF(#combinationsValues, 1, 2, N'')
SET #combinationsFrom = STUFF(#combinationsFrom, 1, 2, N'')
SET #combinationsWhere1 = STUFF(#combinationsWhere1, 1, 2, N'')
SET #combinationsWhere2 = STUFF(#combinationsWhere2, 1, 4, N'')
-- Dynamic statement
DECLARE #stm nvarchar(max)
SET #stm =
N'WITH rcte AS (
SELECT 0 AS Number
UNION ALL
SELECT Number + 1
FROM rcte
WHERE Number < ' + LTRIM(STR(#n)) +
N'), combinations AS (
SELECT ' +
#combinationsSelect +
N', ROW_NUMBER() OVER (ORDER BY ' + #combinationsRowNumber + N') AS ScenarioID
FROM ' + #combinationsFrom +
N' WHERE ((' + #combinationsWhere1 + N') = ' + LTRIM(STR(#n)) + ') AND ' + #combinationsWhere2 +
N')
SELECT c.ScenarioID, v.[value]
FROM combinations c
CROSS APPLY (VALUES ' + #combinationsValues + N') AS v ([value])
WHERE v.[value] > 0'
-- Execute dynamic statement
EXEC (#stm)
If you have sample data like below
You can write query like below
Declare #N int =4
Select T.*
From #T T
cross apply (
select S, SUM(V) Total
From #T
Group By S) Totals
Where Totals.Total=#N and T.S = Totals.S

Split a string into 3 columns - with a twist

I have a very long text string being imported into a table. I would like to split the string up; I have a routine to pull the data into a table, but it creates all the data in a single field in a table.
Example Text:
05/10/2018 21:14,#FXAAF00123456,,Cup 1 X Plane,0.00000,OK,Cup 1 Y Plane,0.00000,OK,Cup 1 Z Plane,40.64252,OK,Cup 2 X Plane,77.89434,OK,..etc
(The test string is much longer than this, in the region of 1500-1700 characters, but with the same structure in the rest of the string).
This data is a series of test measurements, with the name of the value, the value, and the OK/NOK indicator.
I want the results to be stored in a table (variable) with three fields, so the data above becomes:
Field1|Field2|Field3
05/10/2018 21:14|#FXAAF00123456|null|
Cup 1 X Plane|0.00000|OK|
Cup 1 Y Plane|0.00000|OK|
Cup 1 Z Plane|40.64252|OK|
Cup 2 X Plane|77.89434|OK|
...etc
I am using this function to split the string into a table variable:
CREATE FUNCTION [dbo].[fnSplitString]
(
#InputString NVARCHAR(MAX),
#Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT
[Value] = LTRIM(RTRIM(SUBSTRING(#InputString, [Number],
CHARINDEX(#Delim, #InputString + #Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(#InputString)
AND SUBSTRING(#Delim + #InputString, [Number], LEN(#Delim)) = #Delim
) AS y
);
How can this be modified to give the output required above?
You can try this tiny inline splitting approach.
DECLARE #s VARCHAR(MAX)='05/10/2018 21:14,#FXAAF00123456,,Cup 1 X Plane,0.00000,OK,Cup 1 Y Plane,0.00000,OK,Cup 1 Z Plane,40.64252,OK,Cup 2 X Plane,77.89434,OK';
;WITH
a AS (SELECT n=0, i=-1, j=0 UNION ALL SELECT n+1, j, CAST(CHARINDEX(',', #s, j+1) AS INT) FROM a WHERE j > i)
,b AS (SELECT n, SUBSTRING(#s, i+1, IIF(j>0, j, LEN(#s)+1)-i-1) s FROM a WHERE i >= 0)
,c AS (SELECT n,(n-1) % 3 AS Position,(n-1)/3 AS RowIndex,s FROM b)
SELECT MAX(CASE WHEN Position=0 THEN s END) AS part1
,MAX(CASE WHEN Position=1 THEN s END) AS part2
,MAX(CASE WHEN Position=2 THEN s END) AS part3
FROM c
GROUP BY RowIndex
OPTION (MAXRECURSION 0);
The result
part1 part2 part3
05/10/2018 21:14 #FXAAF00123456
Cup 1 X Plane 0.00000 OK
Cup 1 Y Plane 0.00000 OK
Cup 1 Z Plane 40.64252 OK
Cup 2 X Plane 77.89434 OK
Hint
You might change your splitter function to the recursive approach above. On the one side you are limited to a string-length of the count in sys.all_objects which might be smaller than your input. On the other side your approach has to test each and any position, while the recursive approach hops from spot to spot. Should be faster...
This could easily be opened for a multi-character-delimiter if needed...
UPDATE another approach without recursion
...which makes it clumsy to be used in a splitter function (due to OPTION MAXRECURSION(0), which must be placed at the end of the query and cannot live within the function). Try it out:
;WITH
a(Casted) AS (SELECT CAST('<x>' + REPLACE((SELECT #s AS [*] FOR XML PATH('')),',','</x><x>') + '</x>' AS XML))
,b(s,RowIndex,Position) AS
(
SELECT x.value(N'text()[1]','nvarchar(max)')
,(ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) -1) /3
,(ROW_NUMBER() OVER(ORDER BY(SELECT NULL)) -1) %3
FROM a
CROSS APPLY Casted.nodes(N'/x') X(x)
)
SELECT RowIndex
,MAX(CASE WHEN Position=0 THEN s END) AS part1
,MAX(CASE WHEN Position=1 THEN s END) AS part2
,MAX(CASE WHEN Position=2 THEN s END) AS part3
FROM b
GROUP BY RowIndex;
Hint:
Using (SELECT #s AS [*] FOR XML PATH('')) will make this approach save with forbidden characters...
this required a small modification to your fnSplitString function. Add a RowNo to identify the original sequence of the delimited item
CREATE FUNCTION [dbo].[fnSplitString]
(
#InputString NVARCHAR(MAX),
#Delim VARCHAR(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT RowNo = ROW_NUMBER() OVER (ORDER BY Number),
[Value] = LTRIM(RTRIM(SUBSTRING(#InputString, [Number],
CHARINDEX(#Delim, #InputString + #Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_objects) AS x
WHERE Number <= LEN(#InputString)
AND SUBSTRING(#Delim + #InputString, [Number], LEN(#Delim)) = #Delim
) AS y
);
And with that, you can group every 3 rows as one. Also the RowNo can be used to identify the column
The query
; with tbl as
(
select col = '05/10/2018 21:14,#FXAAF00123456,,Cup 1 X Plane,0.00000,OK,Cup 1 Y Plane,0.00000,OK,Cup 1 Z Plane,40.64252,OK,Cup 2 X Plane,77.89434,OK'
)
select Field1 = MAX(CASE WHEN (RowNo - 1) % 3 = 0 THEN Value END),
Field2 = MAX(CASE WHEN (RowNo - 1) % 3 = 1 THEN Value END),
Field3 = MAX(CASE WHEN (RowNo - 1) % 3 = 2 THEN Value END)
from tbl t
cross apply dbo.fnSplitString (t.col, ',')
group by (RowNo - 1) / 3
Can you try following script after you create the SQL split function given in the reference document.
That split function returns the order of splitted string fragments so that information is used for row data
declare #str nvarchar(max) = '05/10/2018 21:14,#FXAAF00123456,,Cup 1 X Plane,0.00000,OK,Cup 1 Y Plane,0.00000,OK,Cup 1 Z Plane,40.64252,OK,Cup 2 X Plane,77.89434,OK'
select
floor(id / 3)+1 rn,
case when id % 3 = 1 then val end Field1,
case when id % 3 = 2 then val end Field2,
case when id % 3 = 0 then val end Field3
from dbo.Split(#str,',')
select
rn,
max(Field1) Field1,
max(Field2) Field2,
max(Field3) Field3
from (
select
floor((id-1) / 3)+1 rn,
case when id % 3 = 1 then val end Field1,
case when id % 3 = 2 then val end Field2,
case when id % 3 = 0 then val end Field3
from dbo.Split(#str,',')
) t
group by rn

Best way to pad section of this string with 0s

This is 2 examples of what the string currently look like:
6731-121-1
9552-3-1
This is what I want to pad them to look like
0006731-121-1
0009552-003-1
So I want them to be padded with 7 zeroes before the first '-' then 3 zeroes between the first and second '-'
What would be the best way to accomplish this in SQL SELECT statement.
SELECT RIGHT('0000000'
+ ISNULL(
LEFT(OE.exception_id, CHARINDEX('-', OE.exception_id)
- 1) ,
''
) ,7) + '-'
+ SUBSTRING(OE.exception_id, CHARINDEX('-', ( OE.exception_id )), 10) exception_id
ParseName() could be an option here
Example
Declare #YourTable Table ([YourCol] varchar(50))
Insert Into #YourTable Values
('6731-121-1')
,('9552-3-1')
Select *
,NewVal = right('0000000'+parsename(replace(YourCol,'-','.'),3),7)
+'-'
+right('000'+parsename(replace(YourCol,'-','.'),2),3)
+'-'
+parsename(replace(YourCol,'-','.'),1)
From #YourTable
Returns
YourCol NewVal
6731-121-1 0006731-121-1
9552-3-1 0009552-003-1
In situations with more than 3 periods
Example: '1.2.3.4.5'
Or any value is empty
3 examples: '1..3', '1.2.3.', '.2'
Parsename will return null for all values. You will need to split the column using a different method.
Here is an alternative to parsename:
DECLARE #table table(col varchar(100))
INSERT #table values('6731-121-1'),('9552-3-1')
SELECT
col,
REPLICATE('0', 8-x) + STUFF(col, x+1, 0,REPLICATE('0', 4 - (y-x))) newcol
FROM #table
CROSS APPLY
(SELECT CHARINDEX('-', col) x) x
CROSS APPLY
(SELECT CHARINDEX('-', col + '-', x+1) y) y
col newcol
6731-121-1 0006731-121-1
9552-3-1 0009552-003-1

Find smallest positive number that is Divisible from given range using SQL

for example : 2520 is the smallest positive that is divided by each number from 1 to 10.
Please help me logic to find smallest positive number from 1 to 20 using SQL
It is 13 693 680 ? http://rextester.com/APWPAS87659
Assuming the result is < 15 000 000
Brute force :
with
number as (
SELECT TOP (15000000)
CONVERT(BIGINT, ROW_NUMBER() OVER (ORDER BY s1.object_id)) as n
FROM
sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
CROSS JOIN sys.all_objects AS s3
)
select
min(n),
max(n),
min(
case
when n%20 + n%19 + n%18 + n%16 + n%15 + n%14 + n%13 + n%12 + n%11 + n%10 + n%9 + n%8 + n%7 + n%6 + n%5 + n%4 + n%3 + n%2 + n%1 = 0 then n
end)
from
number
;
==> very long
Assuming the solution is a multiple of 10 :
with
number as (
SELECT TOP (1500000)
CONVERT(BIGINT, ROW_NUMBER() OVER (ORDER BY s1.object_id)) * 10 as n
FROM
sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
CROSS JOIN sys.all_objects AS s3
)
select
min(n),
max(n),
min(
case
when n%20 + n%19 + n%18 + n%16 + n%15 + n%14 + n%13 + n%12 + n%11 + n%10 + n%9 + n%8 + n%7 + n%6 + n%5 + n%4 + n%3 + n%2 + n%1 = 0 then n
end)
from
number
;
Just x10 faster.
Assuming the result is a multiple of 2520 (smallest positive that is divided by each number from 1 to 10) and 6 000*2 520 > 15 000 000)
with
number as (
SELECT TOP (6000)
CONVERT(BIGINT, ROW_NUMBER() OVER (ORDER BY s1.object_id)) * 2520 as n
FROM
sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
)
select
min(n),
max(n),
min(
case
when n%20 + n%19 + n%18 + n%16 + n%15 + n%14 + n%13 + n%12 + n%11 = 0 then n
end)
from
number
very fast (about x2520 more faster the first proposal).

SQL Summarizing data in final row

I have a query that generates rows of detail information about checks that are issued. In the final output, the data is all concatenated and put into one column (long story short, it needs to be run from Infomaker and exported to text with no delimiting).
Anyway, at the end of these rows I need a summary row that contains two values that are sums of the detail used in the previous rows, along with other values that are hard-coded. This final row also needs to be concatenated to one column, and appear after all the detail rows.
Example of how the summary row should appear with the computed values in brackets:
00123456789999999999940[CHECK AMOUNT SUMMARY][TOTAL NUMBER OF CHECKS (ROWS)]000
Again, no spaces, tabs, or any other delimiters allowed.
I'm stumped on how to achieve this. I have had suggestions of using UNION but I'm not sure exactly how to make that work for this situation.
Current query:
declare #checkDate date = '08/30/13'
select
record = (
-- Checking account number (Record positions 1-9)
cast(cna.BANK_ACCT_NUM as varchar(9)) +
-- Check number (Record positions 10-19) -- must always be nine characters
(case
when LEN(cr.CHECK_NUM_NUMERIC) = 1
then '00000000'
when LEN(cr.CHECK_NUM_NUMERIC) = 2
then '0000000'
when LEN(cr.CHECK_NUM_NUMERIC) = 3
then '000000'
when LEN(cr.CHECK_NUM_NUMERIC) = 4
then '00000'
when LEN(cr.CHECK_NUM_NUMERIC) = 5
then '0000'
when LEN(cr.CHECK_NUM_NUMERIC) = 6
then '000'
when LEN(cr.CHECK_NUM_NUMERIC) = 7
then '00'
when LEN(cr.CHECK_NUM_NUMERIC) = 8
then '0'
else ''
end + cast(cr.CHECK_NUM_NUMERIC as varchar(9))) +
-- Record positions 20-21 - as determined by the bank
'20' +
-- Check amount (Record positions 22-31) -- must always be 10 characters
(case
when LEN(cr.CHECK_AMT) = 1
then '000000000'
when LEN(cr.CHECK_AMT) = 2
then '00000000'
when LEN(cr.CHECK_AMT) = 3
then '0000000'
when LEN(cr.CHECK_AMT) = 4
then '000000'
when LEN(cr.CHECK_AMT) = 5
then '00000'
when LEN(cr.CHECK_AMT) = 6
then '0000'
when LEN(cr.CHECK_AMT) = 7
then '000'
when LEN(cr.CHECK_AMT) = 8
then '00'
when LEN(cr.CHECK_AMT) = 9
then '0'
else ''
end + cast(REPLACE(cr.CHECK_AMT,'.','') as varchar(10))) +
-- Date issued (MMDDYY)(Record positions 32-37)
cast(REPLACE(convert(char(10),cr.CHECK_DTE,101), '/', '') as varchar(10)) +
-- Record positions 38-40 - as determined by the bank
'000' +
-- Payee information line 1 (Record positions 41-90)
cr.CHECK_NAME)
from chk_num_alpha_ctl cna,
chk_reconciliation cr
where ( cr.check_num_alpha = cna.check_num_alpha ) and
( ( cr.check_rtn_void_dte is null ) AND
( cr.check_dte = #checkDate ) ) AND
( cna.bank_acct_num = 'xxxx-xxxx' )
order by cr.check_dte ASC
-- First, you can simplify your query using this type of 'right-justify-zero-fill' statement (adjust if more or less than 9-characters):
select right('000000000' + cast(cr.CHECK_NUM_NUMERIC as varchar(9)),9)
-- Then try something like this (I'm not able to test it, so there may be some adjustments):
UNION
select '00123456789999999999940'
+ right('000000000' + cast(sum(cr.CHECK_AMT) as varchar(9)),9)
+ right('000000000' + cast(count(cr.CHECK_AMT) as varchar(9)),9)
+ '000'
from chk_num_alpha_ctl cna,
chk_reconciliation cr
where ( cr.check_num_alpha = cna.check_num_alpha ) and
( ( cr.check_rtn_void_dte is null ) AND
( cr.check_dte = #checkDate ) ) AND
( cna.bank_acct_num = 'xxxx-xxxx' )
GROUP BY cr.check_dte
order by cr.check_dte ASC