Coldfusion Query of Queries and dateformat error - coldfusion-2016

Documents indicate that I should be able to use the DateFormat() function to format inside of a QoQ,
But I am getting an error - I have tried cast() in addition to normal... I would like to return a query with date parts broken out (month and year) or filter based on datepart to pull back only record that match a month and year
So my objective would look like this in a normal Query.
SELECT
name
,date AS fulldate
,month(date) AS month
,year(date) as year
OR
WHERE
month(date) = arguments.month
and year(date) = arguments.year
However when I try to effectively do this in QoQ - I get a weird error.
Here is what I've tried:
SELECT
directory + '\' + name AS fullpath ,
size ,
DateLastModified ,
dateformat(DateLastModified) AS month
FROM getAllFiles
ORDER BY DateLastModified
Here is the error
Query Of Queries syntax error.
Encountered "(. Incorrect Select Statement, Expecting a 'FROM', but encountered '(' instead, A select statement should have a 'FROM' construct.
I have also tried this (and got the same error)
SELECT
directory + '\' + name AS fullpath ,
size ,
DateLastModified ,
cast( dateformat(DateLastModified,'mm-dd-yyyy') as date ) AS month
FROM getAllFiles ORDER BY DateLastModified
Help greatly appreciated
Cheers

Documents indicate that I should be able to use the DateFormat() function to format inside of a QoQ,
Unfortunately, no. If you're referring to this note in the documentation, it's just poorly worded. I suspect they meant to say, "use [that] function outside the QoQ. For example, when outputting results to the browser withing a query loop".
If you want to convert the date to its original format, use the
DateFormat_ function and apply the "mm/dd/yy" mask._
QoQ's are extremely limited and currently only support these functions:
Conversion functions: CAST()
String functions: UPPER() and LOWER()
Aggregate functions: AVG(), COUNT(), MAX(), MIN()
Could you elaborate on why you're trying to format the string column DateLastModified so we can suggest an alternative?

Related

Display the full Month name from string representation of date stored in “Jan/10/2015” format IN SQL

I want to find the month name in the result from the date given as Jan/10/2015 in SQL.
You can try the DATENAME function in SQL
SELECT DATENAME(month, '2017/09/25');
which in this case will return September.
Date/time functions are notoriously databases dependent -- and you haven't specified the database. That said, your value looks like a string and not a date/time value.
Although you should always store date/time values using appropriate types (which is NOT a string), it looks like you can use string manipulation to do what you want. Most databases support left(), so:
select left(datecol, 3)
In those that don't, use substr() or substring().
You can try this using Oracle:
SELECT TO_CHAR(TO_DATE('Jan/10/2015', 'MM/DD/YYYY'), 'MONTH') as MonthName FROM DUAL;

I need to get month and year from dateColumn

i'm stuck with this part of the query, where I need to get only just month and year from my table.
To put in context, i have tried with "TRUNC_DATE", and Oracle give me back an error like
ORA-00904: "DATE_TRUNC": invalid identifier sql
This piece of query get it from Udacity, but in sql Developer looks like it doesn't work.
When I try search deeper, I find something like convert(char(7), ia.invoice_date(), 120) yearMonth, It still not working and an error came back. ORA-00936: missing expression
I tried a lot of ways but no solutions.
If anyones have an idea o something that could help, I will be grateful.
Here below I paste the fragment of the query for guide help:
SELECT
COUNT(ia.invoice_id) total_de_facturas,
SUM(ia.invoice_amount) monto_total,
convert(char(7), ia.invoice_date(), 120) yearMonth
FROM AP.ap_invoices_all ia
GROUP BY ia.vendor_id;
You ae mixing Oracle syntax with Postgres (date_trunc()) and SQL Server (convert()). Many date functions are vendor-specific, so you learn the relevant syntax for your database.
In Oracle, you would use trunc() to truncate a date to the first day of the month:
trunc(ia.invoice_date, 'mm')
Use the EXTRACT function, try these out to test how it works and use it in your query -
SELECT EXTRACT(YEAR FROM DATE '2020-03-07') FROM DUAL;
SELECT EXTRACT(MONTH FROM DATE '2020-03-07') FROM DUAL;
If you want a string value in YYYY-MM format - which seems to be your intention from the 120 style and the char(7) in the SQL Server-syntax convert() call - then you can just use to_char() with that format model:
to_char(ia.invoice_date, 'YYYY-MM') as yearMonth
You don't need to truncate to the first of the month as you're discarding the day part anyway.

BigQuery: Validate that all dates are formatted as yyyy-mm-dd

Using Google BIGQUERY, I need to check that the values in a column called birth_day_col are the correct and desired date format: YYYY-MM-DD. The values in this column are defined as STRING. Also the values in this column are currently of the following format: YYYY-MM-DD.
I researched a lot on the internet and found an interesting workaround. The following query:
SELECT
DISTINCT birth_day_col
FROM `project.dataset.datatable`
WHERE birth_day_col LIKE '[1-2][0-9][0-9][0-9]/[0-1][0-9]/[0-3][0-9]'
AND country_code = 'country1'
But the result is: "This query returned no results."
I then checked with NOT, using the following code:
SELECT
DISTINCT birth_day_col
FROM `project.dataset.datatable`
WHERE NOT(birth_day_col LIKE '[1-2][0-9][0-9][0-9]/[0-1][0-9]/[0-3][0-9]')
AND country_code = 'country1'
Surprisingly it gave all the values in birth_dat_col, which I have verified and are of the correct date format, but this result coud very much be a coincidence.
And it is very strange (wrong) that I used a query that should result only the wrong format dates, but it actually gives me the correct ones. Everything about these two queries seems like an inversation of each one's role.
The expected result of any query for this business case is to make a count of all incorrect formatted dates (even if currently this is 0).
Thank you for your help!
Robert
A couple of things here:
Read the documentation for the LIKE operator if you want to understand how to use it. It looks like you're trying to use regular expression syntax, but the LIKE operator does not take a regular expression as input.
The standard format for BigQuery's dates is YYYY-MM-DD, so you can just try casting and see if the result is a valid date, e.g.:
SELECT SAFE_CAST(birth_day_col AS DATE) AS birth_day_col
FROM `project`.dataset.table
This will return null for any values that don't have the correct format. If you want to find all of the ones that don't have the correct format, you can use SAFE_CAST inside a filter:
SELECT DISTINCT birth_day_col AS invalid_date
FROM `project`.dataset.table
WHERE SAFE_CAST(birth_day_col AS DATE) IS NULL
The result of this query will be all of the date strings that don't use YYYY-MM-DD format. If you want to check for slashes instead, you can use REGEXP_CONTAINS, e.g. try this:
SELECT
date,
REGEXP_CONTAINS(date, r'^[0-9]{4}/[0-9]{2}/[0-9]{2}$')
FROM (
SELECT '2019/05/10' AS date UNION ALL
SELECT '2019-05-10' UNION ALL
SELECT '05/10/2019'
)
If you want to find all dates with either YYYY-MM-DD format or YYYY/MM/DD format, you can use a query like this:
SELECT
DISTINCT date
FROM `project`.dataset.table
WHERE REGEXP_CONTAINS(date, r'^[0-9]{4}[/\-][0-9]{2}[/\-][0-9]{2}$')
For example:
SELECT
DISTINCT date
FROM (
SELECT '2019/05/10' AS date UNION ALL
SELECT '2019-05-10' UNION ALL
SELECT '05/10/2019'
)
WHERE REGEXP_CONTAINS(date, r'^[0-9]{4}[/\-][0-9]{2}[/\-][0-9]{2}$')
Yet another example for BigQuery Standrad SQL - with use of SAFE.PARSE_DATE
#standardSQL
WITH `project.dataset.table` AS (
SELECT '1980/08/10' AS birth_day_col UNION ALL
SELECT '1980-08-10' UNION ALL
SELECT '08/10/1980'
)
SELECT birth_day_col
FROM `project.dataset.table`
WHERE SAFE.PARSE_DATE('%Y-%m-%d', birth_day_col) IS NULL
with result of list of all dates which are not formatted as yyyy-mm-dd
Row birth_day_col
1 1980/08/10
2 08/10/1980
Google BigQuery's LIKE operator does not support matching digits nor does it uses the [ character in its syntax (I don't think ISO standard SQL does either - LIKE is nowhere near as powerful as Regex).
X [NOT] LIKE Y
Checks if the STRING in the first operand X matches a pattern specified by the second operand Y. Expressions can contain these characters:
A percent sign "%" matches any number of characters or bytes
An underscore "_" matches a single character or byte
You can escape "\", "_", or "%" using two backslashes. For example, "\%". If you are using raw strings, only a single backslash is required. For example, r"\%".
You should use REGEX_CONTAINS instead.
I note that string format tests won't tell you if a date is valid or not, however. Consider that 2019-02-31 has a valid date format, but an invalid date value. I suggest using a datatype conversion function (to convert the STRING to a DATE value) instead.

CDate makes DateAdd formula fail

I hope I will be forgiven for transgressing the rules ever so slightly by asking for a reason, rather than a solution.
I have the following code:
INSERT INTO destinationTable (RecordMonth, ...)
SELECT t1.Expr1, ...
FROM
(
SELECT
CDate(Format("01-" & Right([t1].[Year-Month],2) & "-" & Left([t1].[Year-Month],4),"dd/mm/yyyy")) AS Expr1,
/* ...other fields with no bearing... */
FROM tcsvMonthData AS t1
)
WHERE t1.Expr1 >= DateAdd("m",-6,(SELECT MAX(Expr1) FROM t1))
[Year-Month] in t1 is a varchar-type field.
This script fails, Access gives the following error message: "Data type mismatch in criteria expression."
If I remove the CDate block the script will work. Happy to have found the answer but I don't understand why the error occurs in the first place. CDate constrains a field to a date type. After format the field should be a date type already, so CDate is redundant, but it should not harm (not in my head, at least). Also, as far as I know DateAdd unlike say, Year, does not convert the input field to a string, it should maintain a date type. So what is going on here?
EDIT:
Year-Month describes the month the record occurred in and it looks like this: 2017-11. It is a varchar type and the goal is to have it as a proper datetime field in dd/mm/yyyy format where each month is represented by the first day of that month. So May is 01/05/2018 etc.
You are seriously overcomplicating this. CDate is all you need:
CDate([t1].[Year-Month]) AS Expr1
Edit:
To accept Null values, either filter these out, or use CVDate to either pass Null on:
CVDate([t1].[Year-Month]) AS Expr1
or supply a default value using Nz:
Nz(CVDate([t1].[Year-Month]), Date()) AS Expr1
I have found a solution in sql server please use cdate in place of cast for ms access.
select cast(format(cast('01-' + left('07/23/2018',2) + '-' + right('07/23/2018',4) as date),'dd/MM/yyyy') as date) AS Expr1
change the static date with your column.
It’s been a long time since I have had to use Access but I think the problem isn’t with your use of CDate() but rather the use of Format() on the internal string. Format() needs to operate on a date, but you are giving it a string. Because Format is failing, the surrounding CDate() is failing as well.
You need to use CDate () before Format() like this:
Format(CDate ("01-" & Right([t1].[Year-Month],2) & "-" & Left([t1].[Year-Month],4),"dd/mm/yyyy")) AS Expr1,
You may need to do some tweaking to get that to run but the basic idea should work.
The rejected answer below works because Cast As Date (which is functionally equivalent to CDate) is used both before and after Format() so Format() is being passed a Date. The 2nd Cast in that example is redundant.

Select data in date format

I have a query in which I want to select data from a column where the data is a date. The problem is that the data is a mix of text and dates.
This bit of SQL only returns the longest text field:
SELECT MAX(field_value)
Where the date does occur, it is always in the format xx/xx/xxxx
I'm trying to select the most recent date.
I'm using MS SQL.
Can anyone help?
Try this using ISDATE and CONVERT:
SELECT MAX(CONVERT(DateTime, MaybeDate))
FROM (
SELECT MaybeDate
FROM MyTable
WHERE ISDATE(MaybeDate) = 1) T
You could also use MAX(CAST(MaybeDate AS DateTime)). I got in the (maybe bad?) habit of using CONVERT years ago and have stuck with it.
To do this without a conversion error:
select max(case when isdate(col) = 1 then cast(col as date) end) -- or use convert()
from . . .
The SQL statement does not specify the order of operations. So, even including a where clause in a subquery will not guarantee that only dates get converted. In fact, the SQL Server optimizer is "smart" enough to do the conversion when the data is brought in and then do the filtering afterwards.
The only operation that guarantees sequencing of operations is the case statement, and there are even exceptions to that.
Another solution would be using PATINDEX in WHERE clause.
SELECT PATINDEX('[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]', field_value)
Problem with this approach is you really are not sure if something is date (e.g. 99/99/9999 is not date).
And problem with IS_DATE is it depends on configuration (e.g. DATEFORMAT).
So, use an appropriate option.