DB2 SQL Query to group by week - sql

I am writing an ASP.NET web form page using VB.Net. I am writing code to use on a line graph, but I can't seem to get my query to group by week. Here is my query:
SELECT F42119LA.SDMCU || '-' || F42119LA.SDLNTY AS BranchCode,
AVG(F42119la.SDIVD-F42119LA.SDDRQJ) AS Days,
WEEK(SDTRDJ) AS Day
FROM KAI400.KAIPRDDTA.EXCHBYDATE EXCHBYDATE,
KAI400.KAIPRDDTA.F42119L14 F42119LA
WHERE F42119LA.SDBCRC = EXCHBYDATE.CXCRCD
AND EXCHBYDATE.EXCHDATE = F42119LA.SDTRDJ
AND F42119LA.SDTRDJ>='118006'
AND F42119LA.SDTRDJ<='118096'
AND F42119LA.SDNXTR<>'999'
AND SDIVD <> 0
AND SDDRQJ <> 0
AND F42119LA.SDAEXP <> 0
AND EXCHBYDATE.CXCRDC='USD'
AND F42119LA.SDLNTY IN ('S','W')
AND (SDMCU LIKE '%100' OR SDMCU LIKE '%150')
GROUP BY SDMCU,
SDLNTY,
SDIVD,
F42119LA.SDMCU || '-' || F42119LA.SDLNTY,
WEEK(SDTRDJ)
ORDER BY SDIVD,
SDMCU,
SDLNTY
and this is the code the sql string runs through:
Public Shared Function GetMyDataTableString(SqlString As String, Optional IncDb As Integer = 0) As DataTable
Dim MyConn As OleDbConnection = GetMyConn(IncDb)
Dim DbCmd As New OleDbCommand(SqlString, MyConn)
Dim ReturnDataTable As New DataTable
Try
If Not MyConn.State = ConnectionState.Open Then
MyConn.Open()
End If
Dim Reader As OleDbDataReader = DbCmd.ExecuteReader(CommandBehavior.CloseConnection)
Using Reader
ReturnDataTable.Load(Reader)
End Using
Catch ex As Exception
LogSqlErrors(SqlString, "GetMyDataTableString " & ex.Message.ToString(), IncDb)
If HttpContext.Current.Session("SITEADMIN") = "True" Then
HttpContext.Current.Response.Write("<b>OleFun.GetMyDataTableString, datatable failed</b>---<br />" & ex.ToString)
End If
Finally 'Happens regardless of failing or succeeding
MyConn.Close()
End Try
Return ReturnDataTable
End Function
Whenever I use WEEK(), it gives me this error:
Value in date, time, or timestamp string not valid
ONDATE is a date field in format MM/DD/YYYY. Does anyone know another way to group by week or what might can be giving me this error? Thanks in advance for your responses.

-- date part takes the part of the date as first paramater:
-- you have:
DATEPART(SDTRDJ, wk)
-- needs to be:
DATEPART(wk, SDTRDJ)

DATEPART() might be a function in SQL Server, but it not a function in Db2. You could use WEEK() or WEEK_ISO() which are Db2 functions. https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0005481.html
You could also use EXTRACT if you are on a recent version of Db2 LUW
https://www.ibm.com/support/knowledgecenter/en/SSEPGG_11.1.0/com.ibm.db2.luw.sql.ref.doc/doc/r0053629.html
db2 "values extract(WEEK FROM current date)"
1
-----------
14
1 record(s) selected.
BTW you don't need to group by the concatenation of F42119LA.SDMCU || '-' || F42119LA.SDLNTY, you can group by those columns individually, and only concat in the SELECT.

In DB2, you can group days in same week using following methods:
DATE_PART('WEEK', dateColumn) -> week starts at Saturday
WEEK(dateColumn) -> week starts at Sunday
WEEK_ISO(dateColumn) -> week starts at Monday
DAYS(dateColumn) / 7 -> week starts at Sunday
Notes:
I believe that they work with columns of type DATE as will as TIMESTAMP.
"DAYS(dateColumn) / 7" doesn't get you week number, however it is helpful in grouping by week.
Kindly check your week start day as they differ in their results as following:

Related

Automatically delete rows with Sunday Date

Hello guyz please help.
From snapshot above the "Date" column has sunday date "3/17/2017" and "3/26/2017". I want to delete row with Sunday in the column of "Date" automatically when I imported an attendance log to the datagridview.
so far my code is just to delete one by one:
conn.Open()
cmd.Connection = conn
cmd.CommandText = "DELETE FROM tblEmployeeAttendance WHERE [Date] = '3/17/2017' "
cmd.ExecuteNonQuery()
conn.Close()
but I want to delete upon load to the datagridview.
Try this to change date
While fromatafter.DayOfWeek = DayOfWeek.Saturday OrElse fromatafter.DayOfWeek = DayOfWeek.Sunday
fromatafter = fromatafter.AddDays(-1)
End While
dates.Add(fromatafter.ToString("MM/dd/yyyy"))
You need to assigne the date returned from dates to your variable.
You can use datepart function for sql command
DELETE FROM tblEmployeeAttendance WHERE Datepart(dw,[Date])=1

Datagridview SQL returning no results

Upon loading the form, this code is carried out:
Try
MyConn2.Open()
da2 = New OleDbDataAdapter("Select * from tbl_bookings WHERE DateOfBooking = " & DateTime.Today, MyConn2)
ds2 = New DataSet
da2.Fill(ds2)
DataGridView3.DataSource = ds2.Tables(0)
MyConn2.Close()
Catch ex As Exception
If MyConn2.State <> ConnectionState.Closed Then MyConn2.Close()
End Try
This is supposed to retrieve all results where the date of the booking column is the same as the date today (the current date).
As it stands the datagridview throws up no errors but loads only the field names into the datagridview, not entries that meet the specification (entries with the current date).
Any help would be appreciated, thanks.
I think you need single quotes around the date
da2 = New OleDbDataAdapter("Select * from tbl_bookings WHERE DateOfBooking = "' & DateTime.Today & "'", MyConn2)
I have no knowledge of vb.net, but from the SQL side this could be caused because you are trying to compare a date value (e.g., 4/20/2015) with a date time value (e.g., 4/20/2015 at 11:57 AM). This kind of comparison will look at the time portion of the first date as midnight (4/20/2015 at 12:00 AM), and thus return no matches.
If any of the values in your table have times, or if your vb function returns a time other than midnight, try replacing your SQL with something like the following:
"Select *
from tbl_bookings
WHERE CAST(DateOfBooking AS DATE) = CAST('" & DateTime.Today & "' AS DATE)", MyConn2

Dataset from SQL Query Won't Return Time of 00:00

I am working on a web application in VB.net 2008 with a SQL 2008R2 database on the back end. I am sending a query to SQL through VB to obtain a patient's hospital visit information:
SELECT TOP 1 * FROM visit WITH (NOLOCK) WHERE visit_code = '123' AND start_date <= '07/17/2012' ORDER BY visit_code DESC, start_date DESC
This returns the correct record. However, there is a hold_start_date_time field defined as datetime in the database which contains both the date and time. Everything works great unless the time is midnight - 00:00.
When I run the above query directly in SQL Server Management Studio the field displays correctly. But in the dataset in VB.NET when I look at the datarow the field has only the date with no time at all. A time of anything other than 00:00 populates the dataset correctly.
Unfortunately, midnight is a perfectly valid time for this field. Is there a way I can get it to appear in the dataset?
Dim dsData as DataSet
dsData = GetDataSet(strSql, "visit")
If DataSetRowCount(dsData, "visit") > 0 Then
Dim drData As DataRow
drData = dsData.Tables("visit").Rows(0)
End If
Public Overloads Function GetDataSet(ByVal strSQL As String, ByVal srcTable As String) As DataSet
Dim daData As SqlDataAdapter
daData = New SqlDataAdapter(strSQL, strConnectionString)
daData.Fill(dsData, srcTable)
daData.Dispose()
daData = Nothing
Return dsData
End Function
Any help would be much appreciated.
I guess that the time is there, just not showing up because the visualizer tool (VS Debugger?) don't show if it's 00:00. Try dump in the HTML or window with proper formatting and you will be fine.

How to get records between two dates in vb.net?

All ...
I need to display records that are between the two dates passed in from DateTimePickers.
I am getting records that are NOT in between the dates that I specified from vb.net.
Please go through the code shown below....
Following is the code :
Private Sub btn_Show_Inquiry_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Show_Inquiry.Click
report_viewer_form.Report_viewer_CrystalReportViewer1.ReportSource = Nothing
report_viewer_form.Report_viewer_CrystalReportViewer1.Refresh()
str1 = "SELECT * FROM Inquiry_Details WHERE Inquiry_Date>=#" & dtp_inq_from.Text & "# AND Inquiry_Date<=#" & dtp_inq_to.Text & "#"
If dtp_inq_from.Text > dtp_inq_to.Text Then
MessageBox.Show("FROM_DATE Must Be Less Then TO_DATE.", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Exit Sub
End If
If cn.State <> ConnectionState.Open Then
cn.Open()
End If
da = New OleDbDataAdapter(str1, cn)
report_dataset = New DataSet
da.Fill(report_dataset, "table2")
If MsgBox("Do You Want to Print Report ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
report_viewer_form.Show()
Dim cr As New ReportDocument
cr = New Inquiry_CrystalReport
cr.SetDataSource(report_dataset.Tables("table2"))
report_viewer_form.Report_viewer_CrystalReportViewer1.ReportSource = cr
End If
End Sub
Your problem seems to be in the way you parse passed date parameters to the query and they're probably not in format that Access would recognize as a valid Date type. Try with CDate() function to let Access parse your input values to its internal date type properly. It will accept any valid date expression:
Any expression that can be interpreted as a date, including date
literals, numbers that look like dates, strings that look like dates,
and dates returned from functions. A date expression is limited to
numbers or strings, in any combination, that can represent a date from
January 1, 100 – December 31, 9999.
Your code could thus look like this:
str1 = "SELECT * FROM Inquiry_Details WHERE Inquiry_Date>=CDate('" &
dtp_inq_from.Text & "') AND Inquiry_Date<=CDate('" &
dtp_inq_to.Text & "')"
Another function that you might want to try (if CDate won't cut it) is DateValue():
The required date argument is normally a string expression
representing a date from January 1, 100 through December 31, 9999.
However, date can also be any expression that can represent a date, a
time, or both a date and time, in that range.
The success of these two functions might also depend on input date formatting and system locale.

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using