SQL Select DATES and assign accordingly - sql

I'm using SQL Oracle;
I want to do the following operation, if the YEAR on the column is equal to my current year then I want to assign the value of 0 to a new column called ano, and if it's a year ahead than current year then I want it to be 1 and so on, if it's less than the current year then I want it to be -1 and so on.
The column name that contains the date is KALW_DATE
SELECT *,
CASE
WHEN YEAR(KALW_DATE) > YEAR(NOW()) THEN (YEAR(KALW_DATE) - YEAR(NOW()))
WHEN YEAR(KALW_DATE) < YEAR(NOW()) THEN (YEAR(KALW_DATE) + YEAR(NOW())
ELSE 0
END as ano
FROM tablename;
but I get an error saying "keyword FROM not found where expected" also I'm connecting to DB2, if that changes anything.

You seem to just want:
SELECT (YEAR(KALW_DATE) - YEAR(NOW())) as ano
As for your code, the parentheses do not balance in the second THEN clause.

Oracle does not have a YEAR() function (at least not the version I'm running). You have to use the EXTRACT() function, like this:
SELECT *,
(extract(year from KALW_DATE) - extract(year from current_date)) as ano
FROM tablename;

Related

im trying to use & in a where condition, but this condition is a date, i want to ask for the month and i dont know how to do that

select cod_prestamo, cod_ejemplar, cod_libro,
trunc (extract (month from fec_prestamo)/3) as "trimestre"
**where fec_prestamo &????**
from prestamo;
This is the code, I don't know how to ask for the month.
I tried with this but it obviously doesn´t work:
select cod_prestamo, cod_ejemplar, cod_libro,
trunc (extract (month from fec_prestamo)/3) as "trimestre"
where fec_prestamo like '/&month/ '
from prestamo;
I need to answer with a month and then Oracle show the books that are registered in that month.
Assuming that fec_prestamo is a DATE data type and that you are trying to use a substitution variable to pass in a month name and want to return three columns plus which quarter contains fec_prestamo then you can use:
SELECT cod_prestamo,
cod_ejemplar,
cod_libro,
TO_CHAR(fec_prestamo, 'Q') as "trimestre"
FROM prestamo
WHERE TO_CHAR(fec_prestamo, 'fmMonth') = &month;
Then when you are prompted for the substitution variable you can enter: 'January' (including the surrounding quotes).

SQL Server query date and amount

I am trying to create an SQL query which is based on the following info.
I have an amount bought and sold for each day for articles. I am trying to have a query that shows:
Total "amount" per "article" per "month
"amount" should be split into "positive total" and "negative total", summing up all positive "amount" and all negative "amount" separately.
THe date has the format "yyyy-mm-dd 00:00:00.000"
I tried the following
SELECT article, date, SUM (amount) Total FROM shop group by FORMAT(date, 'yyyy_MM'), article
I get the following message
"date is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
If I take the date out of the query everything works fine and it calculates the totals.
You need a so-called injective function for your dates: way to convert all dates in a month to the same value, and you need to use it both in your SELECT and GROUP BY clauses. LAST_DAY() is a decent function to use. So is DATE_FORMAT(date, '%Y-%m'), by the way.
Try this:
SELECT article, LAST_DAY(date) month_ending, SUM (amount) Total
FROM shop
GROUP BY LAST_DAY(date), article
There's a general writeup of solutions to this problem here.
Original answer for MySQL
There are mainly two mistakes in your query:
FORMAT is a function that converts a number to a string. So, MySQL will convert your date to a number first (which should not even be possible and raise an error, but MySQL does convert it to some number nonetheless) and then make sense of the format 'yyyy_MM', maybe taking MM to mean Myanmar, I don't know. I assume you get a different value for each day, instead of one value per month. You want DATE_FORMAT(date, '%Y-%m') instead.
You try to group by month, but then you display the date. Which date? A month has up to 31 different dates. You must display the month you grouped by instead (i.e. again DATE_FORMAT(date, '%Y-%m')).
As to separating positive and negative amounts, you can use conditional aggrgation, i.e. CASE WHEN inside the aggregation function (SUM).
SELECT
DATE_FORMAT(date, '%Y-%m') AS month,
article,
SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) AS positive_total,
SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END) AS negative_total
FROM shop
GROUP BY DATE_FORMAT(date, '%Y-%m'), article
ORDER BY DATE_FORMAT(date, '%Y-%m'), article;
Updated answer for SQL Server
In SQL Server FORMAT(date, 'yyyy_MM') is a function to get the year and month from a date. The query is hence:
SELECT
FORMAT(date, 'yyyy_MM') AS month,
article,
SUM(CASE WHEN amount > 0 THEN amount ELSE 0 END) AS positive_total,
SUM(CASE WHEN amount < 0 THEN amount ELSE 0 END) AS negative_total
FROM shop
GROUP BY FORMAT(date, 'yyyy_MM'), article
ORDER BY FORMAT(date, 'yyyy_MM'), article;

Teradata Current year and year-1

How to get the dynamic years in the Query for where condition, i need to fetch data for 2017,2018,2019, currently i am hard coding them ( where FSC_YR in (2017,2018,2019) instead i need in a dynamic way. How to do it in teradata.
I tried extract(year from current_date)-2,extract(year from current_date)-1,extract(year from current_date)-3). I am getting error too many expression.
Since you're looking for a range of year numbers, why not just use a BETWEEN?
SELECT *
FROM data
WHERE fsc_yr BETWEEN EXTRACT(year FROM current_date - interval '2' year) AND EXTRACT(year FROM current_date)
But as #dnoeth pointed out in the comments.
To avoid an error when running it on Feb. 29, using INTERVAL might not be the safest method.
But just subtracting from the year number isn't so bad really.
SELECT *
FROM data
WHERE fsc_yr BETWEEN EXTRACT(year FROM current_date)-2 AND EXTRACT(year FROM current_date)
Also note that such error can come from selecting more than 1 column in the query for an IN
For example this would fail:
SELECT * FROM Table1
WHERE Col1 IN (SELECT Col1, Col2 FROM Tabel2)
So if you would use the query for data with a * then it would still result in that error.

SQL - All appointments to current day

I have following query and I get followig error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
I want that dodate is less than date today so if i have appointments which isn't marked as "done" so query will list all of my appointments to current day.
select
dodate, regdate,header,starttime,stoptime,userid,custid,objid,infoid,aname
from fkms.appointment
where
done=0 and del=0
and dodate > (SELECT dodate,
DATEADD(d,dodate - 2440587,'1970-01-01'),
ts,
DATEADD(s,ts,'19700101 01:0:00:000')
FROM fkms.appointment)
and userid='da'
Any tips?
Your query is illegal as the inner SELECT returns more than one value. Change it to:
select
dodate, regdate,header,starttime,stoptime,userid,custid,objid,infoid,aname
from fkms.appointment
where done = 0
and del = 0
and dodate > GETDATE()
and userid ='da';
NOTE: GETDATE() is SQL-SERVER function. IN Oracle you have NOW() and other DBMSs similar functions. Find out which one you need.

Add year to column before compare in SQL query

I am querying a MySQL database and I need to add a year to a column (of type date) before the compare operation.
I would expect is to look something like this:
SELECT count(*) AS count
FROM users
WHERE renewed + 1 year < '2009-12-12'
Use:
SELECT COUNT(*) AS count
FROM USERS u
WHERE DATE_ADD(u.renewed, INTERVAL 1 YEAR) < '2009-12-12'
Reference:
DATE_ADD
You can use the mysql DATE_ADD function:
DATE_ADD(renewed, INTERVAL 1 YEAR)