我们有一张包含以下信息的表格: Quick SQL Fiddle demo
我需要接收"开始日期"的T-SQL代码。和"结束日期,并生成按客户ID和发票类型分组的发票总额,包括日期范围内生成的所有发票和该客户的发票总额(贷方和现金合计)。
例如,如果我们提供开始日期01-10-2012和结束日期10-11-2012,结果应为:
这就是我所拥有的:
Public Function NumberToText(ByVal num As Long) As String
Dim BigNumbers() As String = {"", " Thousand", " Million", " Billion", " Trillion"}
Dim TextParts() As String = {}
If num < 0 Then
Return "Checks cannot be written for negative amounts."
ElseIf num >= 10 ^ ((BigNumbers.Length) * 3) Then
Return "This number exceeds the current maximum value of " & NumberToText(10 ^ ((BigNumbers.Length) * 3) - 1) & "."
End If
Dim LoopCount As Integer = 0
While num >= 1000
ReDim Preserve TextParts(TextParts.Length)
If num Mod 1000 > 0 Then
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num Mod 1000) & BigNumbers(LoopCount)
End If
num = num \ 1000
LoopCount += 1
End While
ReDim Preserve TextParts(TextParts.Length)
TextParts(TextParts.GetUpperBound(0)) = ThreeDigitText(num) & BigNumbers(LoopCount)
If Array.IndexOf(TextParts, "Error") > -1 Then
Return "An unknown error occurred while converting this number to text."
Else
Array.Reverse(TextParts)
Return Join(TextParts)
End If
End Function
Private Function ThreeDigitText(ByVal num As Integer) As String
If num > 999 Or num < 0 Then
Return "Error"
Else
Dim h As Integer = num \ 100 'Hundreds place
Dim tempText As String = ""
If h > 0 Then
tempText = OneDigitText(h) & " Hundred"
End If
num -= h * 100
If num > 0 And Not tempText = "" Then
tempText &= " "
End If
If num > 9 And num < 20 Then
Dim DoubleDigits() As String = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}
Return tempText & DoubleDigits(num - 10)
Else
Dim TensPlace() As String = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}
Dim t As Integer = num \ 10 'Tens place
num -= t * 10
If t > 1 Then
tempText &= TensPlace(t - 2)
If num > 0 Then
tempText &= " "
End If
End If
If num > 0 Then
tempText &= OneDigitText(num)
End If
Return tempText
End If
End If
End Function
Private Function OneDigitText(ByVal num As Integer) As String
If num > 9 Or Num < 0 Then
Return "Error"
Else
Dim SingleDigits() As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}
Return SingleDigits(num)
End If
End Function
它工作正常,但我无法想出一种方法来计算&#34; total2&#34;列,因为我已经按&#34; invoicetype&#34;分组行。
请帮助。
谢谢。
答案 0 :(得分:0)
这应该有效:
SELECT CustomerId, InvoiceType, SUM(Total) As Total
, (
SELECT SUM(Total) FROM Invoices t2 WHERE t2.CustomerId=t1.CustomerId
) AS Total2
FROM Invoices t1
WHERE Date BETWEEN @startdate AND @enddate
GROUP BY CustomerID, InvoiceType