如何选择今天(24)小时数据

时间:2019-12-13 16:21:09

标签: sql sql-server vb.net

我的表中有一列(总计)。我需要总结今天的记录(过去24小时),也需要总结上个月的sql server vb.net

Dim cmd As New SqlCommand
        cmd.Connection = cn
        cmd.CommandText = "Select Sum(Total_Amount) as Total_AmountSum from Table_5"
        Dim adapter As New SqlDataAdapter(cmd)
        Dim table As New DataTable()
        adapter.Fill(table)
        If table.Rows.Count() > 0 Then
            Label11.Text = table.Rows(0)("Total_AmountSum").ToString()
        End If

2 个答案:

答案 0 :(得分:1)

您必须在此处使用 DATEADD

尝试一下

过去24小时

    Dim cmd As New SqlCommand
    cmd.Connection = cn
    cmd.CommandText = "Select Sum(CASE WHEN [Date] BETWEEN DATEADD(day, -1, GETDATE()) AND GETDATE() THEN Total_Amount END) As Total_AmountSum from Table_10"
    Dim adapter As New SqlDataAdapter(cmd)
    Dim table As New DataTable()
    adapter.Fill(table)
    If table.Rows.Count() > 0 Then
        TextBox1.Text = table.Rows(0)("Total_AmountSum").ToString()
    End If

过去1个月

    Dim cmd As New SqlCommand
    cmd.Connection = cn
    cmd.CommandText = "Select Sum(CASE WHEN [Date] BETWEEN DATEADD(mm, -1, GETDATE()) AND GETDATE() THEN Total_Amount END) As Total_AmountSum from Table_10"
    Dim adapter As New SqlDataAdapter(cmd)
    Dim table As New DataTable()
    adapter.Fill(table)
    If table.Rows.Count() > 0 Then
        TextBox1.Text = table.Rows(0)("Total_AmountSum").ToString()
    End If

最后1个弱项

Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "Select Sum(CASE WHEN [Date] BETWEEN DATEADD(ww, -1, GETDATE()) AND GETDATE() THEN Total_Amount END) As Total_AmountSum from Table_10"
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() > 0 Then
    TextBox1.Text = table.Rows(0)("Total_AmountSum").ToString()
End If

答案 1 :(得分:0)

您似乎需要SQL入门课程。去搜索互联网。 W3Schools是一个不错的起点。

与此同时...

select Sum(Total_Amount) as Total_AmountSum
from Table_5
where MyDate between dateadd(hour, -24, getdate()) and getdate()

...或...

select Sum(Total_Amount) as Total_AmountSum
from Table_5
where MyDate > dateadd(hour, -24, getdate())