How do I grab only the latest Invoice Number - c#

I have Invoice Numbers that are stored as nvarchar(25).
Their Format is ‘####AA’
Where #### is the Invoice Number and AA is the Version Number (partial Order Shipping)
I cannot change the format.
I created two Scalar Functions:
CREATE FUNCTION [dbo].[fnNumbersFromStr](#str varchar(8000))
RETURNS int
AS
BEGIN
WHILE PATINDEX('%[^0-9]%',#str)> 0
SET #str = REPLACE(#str, SUBSTRING(#str, PATINDEX('%[^0-9]%', #str), 1), '')
RETURN CAST(#str AS INT)
END
And it’s brother:
CREATE FUNCTION [dbo].[fnStringFromNum](#str varchar(25))
RETURNS varchar(25)
AS
BEGIN
WHILE PATINDEX('%[^a-z]%',#str)> 0
SET #str = REPLACE(#str, SUBSTRING(#str, PATINDEX('%[^a-z]%', #str), 1), '')
RETURN #str
END
I am stalled with this script:
SELECT
strInvoiceNo,
dbo.fnNumbersFromStr(strInvoiceNo) AS [InvoiceNumber],
dbo.fnStringFromNum(strInvoiceNo) AS [InvoiceString]
FROM #TempTable
Which when runs returns:
strInvoiceNo InvoiceNumber InvoiceString
1000A 1000 A
1000B 1000 B
1000C 1000 C
1001A 1001 A
1001B 1001 B
1002AA 1002 AA
1002AB 1002 AB
1003A 1003 A
1004A 1004 A
I just can’t figure out the next step from here. I am stuck.
I would like the select to only return the latest Invoice Versions:
1000C
1001B
1002AB
1003A
1004A
Sql, Lamda or Linq will work fine for me.
Thanks in advance,

Try this:
SELECT
InvoiceNumber + MAX(InvoiceString) As strInvoiceNo
FROM
(
SELECT
dbo.fnNumbersFromStr(strInvoiceNo) AS [InvoiceNumber],
dbo.fnStringFromNum(strInvoiceNo) AS [InvoiceString]
FROM #TempTable
) As tbl
GROUP BY InvoiceNumber

I dont think you need any UDF for this, a simple windowing function query should return what you looking for.
WITH x AS
(
Select *
,ROW_NUMBER() OVER (PARTITION BY InvoiceNumber ORDER BY strInvoiceNo DESC) rn
FROM TableName
)
SELECT strInvoiceNo, InvoiceNumber, InvoiceString
FROM X
WHERE rn = 1
OR
SELECT strInvoiceNo, InvoiceNumber, InvoiceString
FROM
(
Select *
,ROW_NUMBER() OVER (PARTITION BY InvoiceNumber ORDER BY strInvoiceNo DESC) rn
FROM TableName
)x
WHERE rn = 1

Here is it in LINQ (Assuming fnStringFromNum returns a string padded on the left with spaces):
dbContext.YOURTABLE
.GroupBy(x=>UDFFunctions.fnNumbersFromStr(x.AccountNumber))
.Select(x=>x.OrderByDescending(y=>UDFFunctions.fnStringFromNum(y.AccountNumber).FirstOrDefault())
SQL (using current fnStringFromNum):
SELECT
InvoiceNumber + LTRIM(MAX(RIGHT(SPACE(20)+InvoiceString,20))) As strInvoiceNo
FROM
(
SELECT
dbo.fnNumbersFromStr(strInvoiceNo) AS [InvoiceNumber],
dbo.fnStringFromNum(strInvoiceNo) AS [InvoiceString]
FROM #TempTable
) As tbl
GROUP BY InvoiceNumber

Not necessarily the most efficient, but this will work:
select strInvoiceNo
from #TempTable T
where InvoiceString = (select max(invoicestring) from temp1 where invoicenumber = T.invoicenumber)
order by 1
Edit: Sorry....disregard. This will work off of your full result table but may not be what you actually need. Apologies.

Related

How to use string type column in SQL pivot

I have a table like below
Name Year Bonus
---- ----- ------
Ram 2011 1000
Ram 2011 2000
Shyam 2011 'No Bonus'
Shyam 2012 5000
I want to display the total bonus year wise for each person.I tried below query
SELECT [Year],[Ram],[Shyam] FROM
(SELECT Name, [Year] , Bonus FROM Employee )Tab1
PIVOT
(
SUM(Bonus) FOR Name IN (Ram,Shyam)) AS Tab2
ORDER BY [Tab2].[Year]
My Output Should be like below
Name 2011 2012
---- ------ ------
Ram 3000 0
Shyam 'No Bonus' 5000
But it is not working.
Can anyone help me on this?
If your dbms is sql-server you can try to use SUM condition aggregate function in a CTE
then use CAST with coalesce to make it.
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE '%[0-9]%' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = 'No Bonus' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT Name,
coalesce(MAX(CASE WHEN Year = 2011 THEN CAST(total AS VARCHAR(50)) END),'No Bonus') '2011',
coalesce(MAX(CASE WHEN Year = 2012 THEN CAST(total AS VARCHAR(50)) END),'No Bonus') '2012'
FROM CTE
GROUP BY Name
sqlfiddle
If you want to create columns dynamically you can try to use dynamic PIVOT.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE '%[0-9]%' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = 'No Bonus' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT #cols = STUFF((SELECT distinct ',coalesce(MAX(CASE WHEN cnt > 0 and Year = ' + cast(Year as varchar(5)) + ' THEN ''No Bonus'' WHEN Year = ' + cast(Year as varchar(5)) + ' and cnt = 0 THEN CAST(total AS VARCHAR(50)) END),''0'')' + QUOTENAME(Year)
FROM CTE c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = '
;WITH CTE AS(
SELECT Year,Name,
SUM(CASE WHEN Bonus LIKE ''%[0-9]%'' THEN CAST(Bonus AS DECIMAL) ELSE 0 END) total,
COUNT(CASE WHEN Bonus = ''No Bonus'' THEN 1 END) cnt
FROM T
GROUP BY Year,Name
)
SELECT Name, ' + #cols + '
from CTE
GROUP BY Name'
exec(#query)
sqlfiddle
According to your problem the following query is what I understood. Not the ideal solution but this will do.
You can modify the query if you need to make it dynamic.
SELECT [Name]
, case when [2011] = 0 then 'No Bonus' when [2011] is null then '0' else cast([2011] as varchar(50)) end as [2011]
, case when [2012] = 0 then 'No Bonus' when [2012] is null then '0' else cast([2012] as varchar(50)) end as [2012]
FROM
(SELECT Name, [Year] , cast(Bonus as int) Bonus FROM Employee)Tab1
PIVOT
(
SUM(Bonus) FOR Year IN ([2011],[2012])) AS Tab2
ORDER BY [Tab2].[Name]
You need to pass 0 in the table though and then modify in the PIVOT
I would just give up on storing numbers as strings. I don't see the difference between 0/NULL and 'No Bonus', except that the latter makes queries prone to really bad type conversion problems.
So, my advice is to do:
SELECT [Year],[Ram],[Shyam]
FROM (SELECT Name, [Year], TRY_CONVERT(int, Bonus) as Bonus
FROM Employee
) e
PIVOT (SUM(Bonus) FOR Name IN (Ram, Shyam)) AS Tab2
ORDER BY [Tab2].[Year] ;
You probably don't like that solution -- although I really do strongly recommend it because I have spent way too many hours debugging problems with numbers and dates stored as strings.
So, if you persist with storing values as string, use conditional aggregation and a bunch of logic:
select year,
coalesce( sum(case when name = 'Ram'
then convert(varchar(255), try_convert(int, bonus))
end),
'No Bonus'
) as Ram,
coalesce( sum(case when name = 'Shyam'
then convert(varchar(255), try_convert(int, bonus))
end),
'No Bonus'
) as Shyam
from employee e
group by year
order by year;

Given a sorted row of n numbers in SQL server, how do i find at what point the sum of the rows reach the value k?

Assume i got the below row of number and max quantity value is 10.
Quantity BatchValue
2 0
4 0
4 0
6 1
8 2
Summation of 2+4+4 gives me a value less than or equal to max quatity 10 and so the batch value for those rows become 0. The pending rows are 6 and 8. They cannot be summed up to be < max quantity. So they will be seperate. Can we get an sql query or an algorith that can do this?
Here's a nice running sum routine you can use
create table #temp (rowid int identity, quantity int)
insert #temp
select quantity from yourtable order by your order
declare #holding table (quantity int, runningsum int)
declare #quantity int
declare #running int=0
declare #iterator int = 1
while #iterator<=(select max(rowid) from #temp)
begin
select #quantity=quantity from #temp where rowid=#iterator
set #running=#quantity+#running
insert #holding
select #quantity, #running
set #iterator=#iterator+1
end
Edited code from Daniel Marcus above to give the actual response requested in query.
CREATE TABLE #temp(rowid int identity(1,1), quantity int)
INSERT INTO #temp
SELECT 2
UNION ALL SELECT 4
UNION ALL SELECT 4
UNION ALL SELECT 6
UNION ALL SELECT 8
declare #batchValue int = 0 ,#maxquantity int = 10
declare #holding table (quantity int, batchvalue int)
declare #quantity int
declare #running int=0
declare #iterator int = 1
while #iterator<=(select max(rowid) from #temp)
begin
select #quantity=quantity from #temp where rowid=#iterator
set #running=#quantity+#running
-- Newly added condition
if (#running > #maxquantity) BEGIN
SET #batchValue = #batchValue + 1 -- increment the batch value
insert #holding select #quantity, #batchValue
SET #running = #quantity -- reset the running value
END
ELSE
insert #holding select #quantity, #batchValue
set #iterator=#iterator+1
end
SELECT * FROM #holding
DROP TABLE #temp
Hope the snippet works for your purpose. I tested this in SQL azure and provides the result you mentioned.
--The below query will help you if you working on sql server 2012 or higher
CREATE TABLE #RUN_TOT(ID INT)
INSERT INTO #RUN_TOT VALUES(2),(4),(4),(6),(8)
;WITH CTE AS
(
SELECT ID,
ROW_NUMBER() OVER(ORDER BY ID) RNUM,
CASE
WHEN SUM(ID) OVER(ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) <=
(SELECT MAX(ID) FROM #RUN_TOT) THEN 0
ELSE
ID
END VAL
FROM #RUN_TOT
)
SELECT ID,VAL FROM CTE WHERE VAL=0
UNION ALL
SELECT ID,ROW_NUMBER() OVER(ORDER BY VAL) VAL FROM CTE WHERE VAL<>0

DISTINCT query not working its give me repeated columns on output

Buddy
i have one query of MSSQL.
that is like this..
SELECT DISTINCT resource.locationurl,
resource.resourcename,
resource.anwserid,
checktotal.total
FROM resource
INNER JOIN (SELECT Count(DISTINCT anwserid) AS total,
resourcename
FROM resource AS Resource_1
WHERE ( anwserid IN (SELECT Cast(value AS INT) AS Expr1
FROM dbo.Udf_split(#sCategoryID, ',')
AS
udf_Split_1) )
GROUP BY resourcename) AS checktotal
ON resource.resourcename = checktotal.resourcename
WHERE ( resource.anwserid IN (SELECT Cast(value AS INT) AS Expr1
FROM dbo.Udf_split(#sCategoryID, ',') AS
udf_Split_1)
)
AND ( checktotal.total = #Total )
ORDER BY resource.resourcename
I run this query but its give me repeated column of Resource.LocationURL.
you can check it live hear http://www.ite.org/visionzero/toolbox/default2.aspx
check in above link where you can fire select some category but result was not distinct..
i try most of my but now i am out of mind please help me with this.
You misunderstand what DISTINCT means when you are fetching more than one column.
If you run this query:
SELECT DISTINCT col1, col2 FROM table
You are selected every different combination. An acceptable result would be
value 1_1, value 2_1
value 1_1, value 2_2,
value 2_1, value_2_1
In this example, value 1_1 appears twice, but the two columns combined are unique.
My guess is that you are actually attempting to perform a grouping:
SELECT resource.locationurl,
resource.resourcename,
resource.anwserid,
Sum(checktotal.total)
FROM resource
INNER JOIN (SELECT Count(DISTINCT anwserid) AS total,
resourcename
FROM resource AS Resource_1
WHERE ( anwserid IN (SELECT Cast(value AS INT) AS Expr1
FROM dbo.Udf_split(#sCategoryID, ',')
AS
udf_Split_1) )
GROUP BY resourcename) AS checktotal
ON resource.resourcename = checktotal.resourcename
WHERE ( resource.anwserid IN (SELECT Cast(value AS INT) AS Expr1
FROM dbo.Udf_split(#sCategoryID, ',') AS
udf_Split_1)
)
AND ( checktotal.total = #Total )
GROUP BY resource.locationurl,
resource.resourcename,
resource.anwserid
First of all, the site you linked doesn't do anything.
Second, DISTINCTensures unique rows. It will not make the values in all the columns unique as well. Just think about it! How would it work? You have two rows with the same locationurl field, but with otherwise distinct elements. Which one do you not include?
Lastly, please take greater care in phrasing your questions.
as I see your query is select DISTINCT on multi columns,
so if any record has at least one col difference then it pass the DISTINCT condition
Ex:
record1 : locationurl | resourcename | anwserid | Sum(checktotal.total)
loc1 res1 1 100
record2 : locationurl | resourcename | anwserid | Sum(checktotal.total)
loc1 res1 2 100

SQL Server : how to detect unregarded values from a range of integers

I have a problem, in example: I have a range of ids of integers (from 1 to 1000), this range supposed to be ids in a SQL Server table, and I want to detect which numbers of this range are not in the table, and sorry for my bad english, thank you
another simpler option would be to use the following query
SELECT number
FROM master..spt_values
WHERE number BETWEEN 1 AND 1000
AND NOT EXISTS ( SELECT 1
FROM Your_Table t --<-- your table where you are checking
WHERE t.ID = number) -- the missing values
GROUP BY number
The above solution is only good if you are looking for around 1000 values. For more values you would need to modify it little bit, something like
-- Select the maximum number or IDs you want to check
DECLARE #Max_Num INT = 10000;
;WITH CTE AS
(
SELECT TOP (#Max_Num) ROW_NUMBER() OVER ( ORDER BY (SELECT NULL)) numbers
FROM master..spt_values v1 cross join master..spt_values v2
)
SELECT c.numbers
FROM CTE c
WHERE NOT EXISTS (SELECT 1
FROM Your_table t
WHERE t.ID = c.numbers)
One way to find "holes" is to generate a list of all possible values and then look for the ones that aren't there. If you can survive with a list of a missing value and then the number of subsequent values following it, you can do this with another method.
SQL Server 2012+ supports lead() and lag(). The following gets almost everything, except for initial missing values:
select t.id + 1 as missingid,
(coalesce(t.nextid, 1000) - t.id - 1) as nummissing
from (select t.*, lead(t.id) over (order by t.id) as nextid
from table t
t.id between 1 and 1000
) t
where t.nextid > t.id + 1 or
(t.nextid is null and t.id <> 1000)
You can get these with a little piece of special logic:
select (case when t.previd is null then 1
else t.id + 1
end) as missingid,
(case when t.previd is null then t.id - 1
else (coalesce(t.nextid, 1000) - t.id - 1)
end) as nummissing
from (select t.*, lead(t.id) over (order by t.id) as nextid,
lag(t.id) over (order by t.id) as previd
from table t
where t.id between 1 and 1000 and
) t
where (t.nextid > t.id + 1 or
(t.nextid is null and t.id <> 1000)
(t.previd is null and t.id <> 1)
)
This sounds like one of the many scenarios where it is helpful to have a numbers table:
SELECT *
FROM lkp_Numbers a
WHERE NOT EXISTS (SELECT 1
FROM YourTable b
WHERE a.num = b.Id)
AND num <= 1000
I use this to create a numbers table:
DROP TABLE lkp_Numbers
DECLARE #RunDate datetime
SET #RunDate=GETDATE()
SELECT TOP 1000 IDENTITY(int,1,1) AS Num
INTO lkp_Numbers
FROM sys.objects s1, sys.objects s2, sys.objects s3
ALTER TABLE lkp_Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Num)
That method for creating a numbers table was found here: What is the best way to create and populate a numbers table?

Datatype for System.Version in sql server

What is the best way to store System.Version in SQL Server?
When I use varchar type, result of order by asc is:
1.0.0.0
11.0.0.0
12.0.0.0
2.0.0.0
you can use a varchar column
you could order like this
SELECT *
FROM t_version
ORDER BY CAST('/' + vid + '/' AS HIERARCHYID)
SQL fiddle is not working today , other wise I could have showed a demo
Please run this for testing
SELECT * FROM
( VALUES
( '1.0.0.0' ),
( '11.0.0.0' ),
('12.0.0.0'),
('2.0.0.0') ) AS vid ( vid )
ORDER BY CAST('/' + vid + '/' AS HIERARCHYID)
Just store it as a normal varchar, which is good for versions up to 4 parts using PARSENAME to split the string and order by 4 separate columns.
i.e.
ORDER BY PARSENAME(version,4),
PARSENAME(version,3),
PARSENAME(version,2),
PARSENAME(version,1)
To support ordering among mixed lengths versions (e.g. '1.2' vs '1.2.3.4'), a mapping to a decimal can be performed (as inline table valued functions).
create function Common.ufn_OrderableVersion(#pVersion nvarchar(100))
returns table
as
/*---------------------------------------------------------------------------------------------------------------------
Purpose: Provide a mapping from Versions of the form 'a.b.c.d', 'a.b.c, 'a.b', 'a', null to
an orderable decimal(25, 0)
Since Parsename() doesn't apply easily to mixed length comparisions (1.2 vs 1.2.3.4)
Test Cases:
select * from Common.ufn_OrderableVersion(null); -- null
select * from Common.ufn_OrderableVersion('0'); -- 1000000000000000000000000
select * from Common.ufn_OrderableVersion('1'); -- 1000001000000000000000000
select * from Common.ufn_OrderableVersion('1.2.3.4'); -- 1000001000002000003000004
select Version
from
(
select '1.3.5.3' as Version
union all
select '1.2.5.3' as Version
union all
select '1.1.5.3' as Version
union all
select '1.3.5.2' as Version
union all
select null as Version
union all
select '' as Version
union all
select '2' as Version
union all
select '1.2' as Version
union all
select '1' as Version
) v
order by (select Value from Common.ufn_OrderableVersion(Version))
Modified By Description
---------- -------------- ---------------------------------------------------------------------------------------
2015.08.24 crokusek Initial Version
---------------------------------------------------------------------------------------------------------------------*/
return
-- 25 = 1 + VersionPositions * MaxDigitsPerSegment
select convert(decimal(25,0), '1' +
stuff((select format(Value, '000000')
from
(
select convert(int, Value) as Value, RowNumber
-- Support empty string and partial versions. Null maps to null
from Common.ufn_SplitUsingXml(#pVersion + '.0.0.0.0', '.') -- pad right
where RowNumber <= 4 -- trim right
) as v
order by RowNumber
for xml path ('')
), 1, 0, '')
) as Value
go
Dependency:
create function Common.ufn_SplitUsingXml
(
#pList nvarchar(max),
#pDelimiter nvarchar(255)
)
returns table
as
/*---------------------------------------------------------------------------------------------------------------------
Purpose: Split an Identifier using XML as an inline table valued function.
Using the SQL Server CLR (C#) capability would be the most efficient way to support this.
Warnings: Will not work if the input contains special XML characters like '<', '>' or '&'.
Caller must add "option (maxrecursion 0)" for lists greater than 100 (it can't be added within the ufn)
Modified By Description
---------- -------------- ---------------------------------------------------------------------------------------
2015.08.24 inet http://sqlperformance.com/2012/07/t-sql-queries/split-strings
---------------------------------------------------------------------------------------------------------------------*/
return
(
select Value = y.i.value('(./text())[1]', 'nvarchar(4000)'),
row_number() over (order by (select null)) as RowNumber
from
(
select x = convert(XML, '<i>'
+ replace(#pList, #pDelimiter, '</i><i>')
+ '</i>').query('.')
) AS a cross apply x.nodes('i') AS y(i)
-- option (maxrecursion 0) must be added by caller for lists greater than 100
);
go
Comparison:
alter function Common.ufn_CompareVersions
(
#pVersionA nvarchar(100),
#pVersionB nvarchar(100)
)
returns table
as
/*---------------------------------------------------------------------------------------------------------------------
Purpose: Compare Version of the form 'A.B.C.D'.
Comparing versions of different lengths is also supported 'A.B'.
Test Cases:
select Result from Common.ufn_CompareVersions('1', null) -- 1
select Result from Common.ufn_CompareVersions(null, '1') -- -1
select Result from Common.ufn_CompareVersions('1', '1') -- 0
select Result from Common.ufn_CompareVersions('1', '2') -- -1
select Result from Common.ufn_CompareVersions('2', '1') -- 1
select Result from Common.ufn_CompareVersions('1', '1.2') -- -1
select Result from Common.ufn_CompareVersions('1.2', '1') -- 1
select Result from Common.ufn_CompareVersions('1.2.3.4', '1.2.3.4') -- 0
select Result from Common.ufn_CompareVersions('1.2.3', '1.2.3.4') -- -1
select Result from Common.ufn_CompareVersions('1.2.3.4', '1.2.3') -- 1
select Result from Common.ufn_CompareVersions('1.9.3.4', '1.2.3.4') -- 1
select Result from Common.ufn_CompareVersions('1.2.3.4', '1.9.3.4') -- -1
select Result from Common.ufn_CompareVersions('1.002', '1.2') -- 0
select Result from Common.ufn_CompareVersions('1.2', '1.2.0') -- 0
Modified By Description
---------- ----------- ------------------------------------------------------------------------------------------
2015.08.24 crokusek Initial Version
---------------------------------------------------------------------------------------------------------------------*/
return
with Compares as
(
select (select IsNull(Value, 0) from Common.ufn_OrderableVersion(#pVersionA)) as A,
(select IsNull(Value, 0) from Common.ufn_OrderableVersion(#pVersionB)) as B
)
select case when A > B then 1
when A < B then -1
else 0
end as Result
from Compares
go

Categories