我的发票号码存储为nvarchar(25)。
他们的格式为'#### AA' 其中####是发票编号,AA是版本号(部分订单发货) 我不能改变格式。
我创建了两个标量函数:
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
这是兄弟:
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
我对这个剧本感到困惑:
SELECT
strInvoiceNo,
dbo.fnNumbersFromStr(strInvoiceNo) AS [InvoiceNumber],
dbo.fnStringFromNum(strInvoiceNo) AS [InvoiceString]
FROM @TempTable
运行时返回:
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
我无法从这里弄清楚下一步。我被卡住了。
我希望select只返回最新的Invoice Versions:
100℃
1001B
1002AB
1003A
1004A
Sql,Lamda或Linq对我来说会很好。
提前致谢,
答案 0 :(得分:1)
试试这个:
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
答案 1 :(得分:1)
我认为你不需要任何UDF,一个简单的窗口函数查询应该返回你想要的东西。
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
答案 2 :(得分:1)
这是在LINQ中(假设fnStringFromNum返回一个用空格填充左边的字符串):
dbContext.YOURTABLE
.GroupBy(x=>UDFFunctions.fnNumbersFromStr(x.AccountNumber))
.Select(x=>x.OrderByDescending(y=>UDFFunctions.fnStringFromNum(y.AccountNumber).FirstOrDefault())
SQL(使用当前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
答案 3 :(得分:0)
不一定效率最高,但这可行:
select strInvoiceNo
from @TempTable T
where InvoiceString = (select max(invoicestring) from temp1 where invoicenumber = T.invoicenumber)
order by 1
编辑:抱歉......无视。这将取决于您的完整结果表,但可能不是您实际需要的。道歉。