oracle sql developer(4.0.0.12) returns wrong date - sql

It seems that a query of mine returns wrong results, and I'm not sure why. I don't yet rule out the possibility that the SQL is actually doing something else then what I expect/want it to do since I haven't used SQL for a time now.
I post it here because I'm kind a stuck with the why it returns wrong results sometimes.
The error is in the MIN(FIRM.account_recharge.X__INSDATE) (or at least the ones I noticed)
SELECT
FIRM.customer.CUSTOMER_ID,
FIRM.customer.CORPORATION,
FIRM.customer.CUSTOMER_NAME_PREFIX,
FIRM.customer.CUSTOMER_NAME,
FIRM.account.ACCOUNT_TYPE,
FIRM.account.ACCOUNT_TYPE,
FIRM.customer.LANGUAGE,
FIRM.customer.VALIDATED,
FIRM.account.X__INSDATE,
SUM(FIRM.account_recharge.GROSS_VALUE) SUM_FELTOLTESEK,
MIN(FIRM.account_recharge.X__INSDATE),
INNER JOIN FIRM.account
ON FIRM.customer.CUSTOMER_ID = FIRM.account.CUSTOMER
INNER JOIN FIRM.customer_address
ON FIRM.account.CUSTOMER = FIRM.customer_address.CUSTOMER
INNER JOIN FIRM.account_recharge
ON FIRM.account.ACCOUNT_ID = FIRM.account_recharge.ACCOUNT
GROUP BY FIRM.customer.CUSTOMER_ID,
FIRM.account.X_INSDATE,
FIRM.customer.CORPORATION,
etc,etc
HAVING MIN(FIRM.account_recharge.X__INSDATE) BETWEEN to_date('2014-JAN. -01','YYYY-MON-DD') AND to_date('2014-DEC. -31', 'YYYY-MON-DD');
This code should return information abut our customers, their sum account 'recharging'/'replenishing'/'paying in' , sorry not sure of what word to use here. and their first payment/money upload to their account in 2014. Yet sometimes the return values seems to just ignore the actual first time our client paid in money, and shows the second or third date. (my random manual check returned that around 1/10 of the time the returned values are wrong.)
A costumer of ours can have more the one account linked to him. I'm using Oracle SQL developer (4.0.0.12) please ask if you would like to know anything else about this pickle im in.
Otherwise It seems to work nicely, but if you have any other tuning tip, I would be glad to hear them.
Thank you for your help!

HAVING MIN(FIRM.account_recharge.X_INSDATE) BETWEEN '14-JAN. -01' AND '14-DEC. -31'
This is definitely incorrect. You are comparing dates. so, you must convert the string literal explicitly into a date using TO_DATE and proper format mask.
For example,
HAVING MIN(FIRM.account_recharge.X_INSDATE)
BETWEEN to_date('2014-JAN-01','YYYY-MON-DD')
AND to_date('2014-DEC-31', 'YYYY-MON-DD')
Also, do not use YY to denote the year. You don't have to re-invent the Y2K bug again. Always use YYYY format for an year. Else, if you are stuck with YY values for year, then use RR format. But, I would insist, always use YYYY format for year.

Related

SQL Server : best practice query for date manipulation

Long time listener, first time caller.
At work we have all of the date columns for most tables stored in as a simple "string" (varchar) formats. Such as yyyymmdd (eg. 20220625) or yyyymm (202206) etc.
Now for a lot of queries that are time based we need to compare to current date, or some fixed offset from current date.
Now two obvious versions that I know of to get current utc date into either of those formats are the following (for yyyymm as example):
SELECT LEFT(CONVERT(VARCHAR, GETUTCDATE(), 112), 6) ...
SELECT CONVERT(VARCHAR(6), GETUTCDATE(), 112) ...
I'm wondering if anyone knows of a better way, either both idiomatically or performance wise to convert those, and/or is there anything wrong with the second one to be worried about versus the first one in regards to either security/reliability etc? The second one definitely satisfies my code golf sensibilities, but not if it's at the expense of something I'm unaware of.
Also for some extra context the majority of our code runs in SQL Server or T-SQL, BUT we also need to attempt to be as platform agnostic as possible as there are customers on Oracle and/or Mysql.
Any insight/help would be highly appreciated.
There is no problem with either approach. Both work just fine. It is a matter of personal preference which to choose. The first looks more explicit, the second is shorter and thus easier to read maybe. As to performance: You want to get the current day or month only once in a query, so the call doesn't realy affect query runtime.
As to getting this platform agnostic is quite a different story. SQL dialects differ. Especially when it comes to date/time handling. You already notice that SQL Server's date functions are quite restricted. In Oracle and MySQL you would simple state the format you want (TO_CHAR(SYSDATE, 'YYYYMM') in Oracle and DATE_FORMAT(CURRENT_DATE, '%Y%m') in MySQL). But you also see that the function calls differ.
Now, you could write a user defined function GET_CURRENT_MONTH_FORMATTED for this which would return the string for the current month, e.g. '202206'. Then you'd have the different codes hidden in that function and the SQL queries would all look the same. The problem, though, is how to tell the DBMS that the function result is deterministic for a particular timestamp? If you run the query on December 31, 2022 at 23:50 and it runs until January 1, 2023 at 0:20, you want the DBMS to call this function only once for the query resulting in '202212' and not being called again, suddenly resulting in another string '202301'. I don't even know whether this is possible. I guess it is not.
I think you cannot write a query that does what you want and looks the same in all mentioned DBMS.

Where in my query to place the CONVERT to convert DateTime to Date

Just learning SQL and I've searched many options about converting a DateTime into a Date, and I do not want current date. It's a super simple query from this website: https://sqlzoo.net/wiki/Guest_House_Assessment_Easy
SELECT booking_date, nights
FROM booking
WHERE guest_id=1183
But the output is with the timestamp and I just want the date. I've searched so many forums and tried all their suggestions, including this:
SELECT CONVERT(varchar(10), <col>, 101)
So I've done:
SELECT CONVERT(varchar(10), booking_date,101), nights
FROM booking
WHERE guest_id=1183
But I'm getting syntax errors. This is probably so simple and you'll all think me an idiot, but I'd greatly appreciate help. It's driving me nuts.
When I fiddled about at your sqlzoo link I got the error
execute command denied to user 'scott'#'localhost' for routine 'gisq.to_date'`.
When I googled gisq.to_date I got this link https://sqlzoo.net/wiki/Format_a_date_and_time
Which has examples of how this dialect represents dates. See if you can work it out. Something like this:
SELECT date_format(booking_date,'%d/%m/%Y')
FROM booking
You didn't post the error in your question which is a big mistake. When you get an error message, you actually have something to work from.
It is also very important to note that the query above returns a string, not a date. It's only good for display, not for date arithmetic
TBH that seems like a terrible site to learn on as it gives no clues about the dialect. it looks like Oracle but to_date and trunc don't work.
The use of convert() suggests that you think you are uinsg SQL Server. If you only want the date component of a date/time data type, then you can use:
SELECT CONVERT(DATE, booking_date), nights
FROM booking
WHERE guest_id = 1183;
The syntax error suggests that you are not using SQL Server.
CONVERT() is bespoke syntax for SQL Server. Examples of similar functionality in other databases are:
DATE(booking_date)
TRUNC(booking_date)
DATE_TRUNC('day', booking_date)
In addition, what you see also depends on the user-interface.
In your case, the data is being stored as a date with no time component, but the UI is showing the time. For that, you want to convert to a string. That site uses MariaDB -- which is really a flavor of MySQL-- and you would use:
DATE_FORMAT(booking_date, '%Y-%m-%d')

Microsoft Access 2010 Date Conversion

I don't have much experience so I apologize in advance for a potentially dumb question. I did not create these tables nor the queries that have been used in the past. With that said --
For the past several months I have been using a date conversion query that was given to me to update columns from an integer to a date. It used to work just fine and I swear everything is the same for my latest data extractions, but at some point the dates started getting wonky. For example, a typical date column might look like:
58222
58158
59076
58103
And the conversion query looks something like this:
IIf([D_posting]<>0,[D_posting]-18261,0)
And returns the above dates as:
05/27/2059
03/24/2059
09/27/2061
01/28/2059
Which obviously is wrong. The situation kind of reminds me of how I remember we generated random numbers in C++ (which was a long time ago), but for the life of me I can't figure out how to reverse engineer the correct subtraction factor without a reference point.
I also tried using the CDate() function instead, and it resulted in a bunch of future dates also, leading me to wonder if there's something else wrong. I work for a small physicians group so it might be something in the Electronic Health Records software, but I'd like suggestion on what I should check to make sure it's nothing that I've done.
You could create a query that uses the 'cdate' function (see below) to return the date. You can modify the code so that it subtracts the offset (maybe 18261?)
In the immediate window of VBA you can tinker with the following:
The 'cdate' will take a number and convert it to a date:
?cdate(41925)
10/13/2014
The 'cdbl' will take a date and convert to a number.
?CDbl(Date())
41926

Constructing an sql Query to get records betwen two dates

I'm trying to filter out and report records in a database that fall between a specified date range. I'm there are other threads here on how to do something similar, but my dates are stored as date timestamps (which is why I think the issue is arising)
My current query is as follows:
"SELECT * FROM JOURNAL WHERE Date_Time>'10/10/2013 00:00:00'"
(Note that journal is the name of the table I'm pulling the data from and date_time is the field in which the date is stored. I'm aware the query doesn't quite do what I want it to yet, but I was just testing out a simpler case at first.)
When I run this query (as part of an excel macro), excel reports that it can't find any records even though I know their are records past this date. Does anyone know how to do this properly?
Edit: I've got it, it was an issue unrelated to the query (something else in the macro) Thanks so much for the help (changing the date format worked)
have you tried other date format? like this:
"SELECT * FROM JOURNAL WHERE Date_Time>'2013-10-10:00:00:00'"
A simple between statement is what you need:
SELECT * FROM JOURNAL WHERE Date_Time between '10/10/2013 00:00:00' and '[otherdate]'
You need to run this to check for one important thing: If the server is running the BETWEEN as inclusive or not. If it's inclusive, both dates are included. If not, the range will begin either before or after one or both.
I've seen SQL servers that are the same in every respect actually treat this condition differently. So it's a good idea to check that.

SQL - User input in query

I have this. "Detail all films shown by the club between any two given dates, inputted by the user. For example a club member must be able to input a start date and an end date for the parameters for the query"
Now, how would I go about doing the user input? Only way I can think of would to be using php or something with a html form getting the values and then submitting them as variables in the query. However, that's not what is needed. So, how is this done so the query would ask for values? Or can't you?
My query so far looks like so.
SELECT film.title, film.desc, show.sdate, show.fdate
FROM film
INNER JOIN show
ON film.ID=show.filmID
WHERE sdate = '&userstart' AND fdate = '&userend'
How do I go about with the user input? Also, is the query correct? I have no way of testing, I only have a design not an implementation.
Thanks a lot
Edit: Using Windows system, MS SQL Server.
Here's the code for a stored procedure:
CREATE PROCEDURE SomeName(#UserStart DATETIME, #UserEnd DATETIME)
AS BEGIN
SELECT somestuff
FROM sometable
WHERE somedate BETWEEN #UserStart AND #UserEnd
END
#Kyle93 -
Looking at your WHERE Clause:
WHERE sdate = '&userstart' AND fdate = '&userend'
This will only get you Films that had a sdate(Start Date?) equal to the date value entered.
You might want to use Greater than, Less Than operators....
Such as:
WHERE sdate <= '&userend' AND fdate >= '&userstart'
(Note comparing sdate to UserEnd Date to make sure Film Showing started EARLIER than the UserEnd Date...etc)
This way - when a show starts OR ends within the date range - it will be selected.
Are you familiar at all with LINQ? It's a way to make db calls from c#.
-- I would handle this with HTML as you thought, and use Javascript/Ajax to reference c# code that uses LINQ for db calls. Might be a bit complicated however, if you're not familiar with much of that. I can recommend good tutorials if interested tho.