I need to get month and year from dateColumn

Viewed 915

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;

3 Answers

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.

Related