Compare month extract from date, same year or next year - sql

This SQL statement working fine for the last year, to selecting data where current month is greater than Subquery Max month match by ciient_id. Now, Subquery return Max month is 12 for the last year whether comparing current month for this year which is 1. That why the SQL statement return 0 record.
I have to find out client_id, those who are not exist in the Subquery for the current month. Either I can compare with date. Please Help me to get out of here.
SELECT c.id, p.pkg_rate AS amount
FROM tbl_client AS c
INNER JOIN tbl_package AS p ON c.pkg_id = p.id
WHERE c.status=1 AND
Month(Date())>(SELECT Month(Max([due_month])) FROM tbl_payment_due WHERE
c.id=client_id);

One approach is to format the date into a string first.
Format(Date(),"yyyymm") > (SELECT Format(Max([due_month]),"yyyymm") FROM tbl_payment_due WHERE c.id=client_id)
A second option is to add a check for the year in the WHERE clause (note: my parenthesis may be off a bit).
(Year(Now()) > (SELECT Year(Max([due_month])) FROM tbl_payment_due WHERE c.id=client_id)) OR
((Year(Now()) = (SELECT Year(Max([due_month])) FROM tbl_payment_due WHERE c.id=client_id)) AND (Month(Date())>(SELECT Month(Max([due_month])) FROM tbl_payment_due WHERE c.id=client_id)))

Related

How can I create a query in SQL Server, using as base table a date function and linking it to another table?

I am trying to create a query using a function of dates and a table of shifts, which can show me the shifts of workers each day, when I have a shift or rest depending on the day,
What do I have: I have a date function that gives me a range of dates that I add, I attach an example:
I have a table of shifts, with only the days that a person has a shift, if a day has a break, the date or the row does not appear, I attach an example:
It can be seen that in the shift table there are only records when a person has a shift.
Problem: when I perform the join between the function and the shift table through the date field, the result is that it only shows me the record when it has a shift and no, it does not put the date when it has a break, I attach an example:
Desired result:
The idea is that when the worker has a break, the row will be blank, only showing the date and his ID, or saying the word break.
I hope you can help me. Thank you so much.
Use LEFT JOIN for avoiding few date missing which has transaction in table.
Use two subquery here for getting appropriate result. In first subquery function CROSS JOIN with transaction table where retrieving distinct id_trabajador for specified date range. If it doesn't do then id will blank in result where no transaction exists for specific id in a certain date. In second subquery retrieve all rows for given date range.
-- SQL Server
SELECT tmp.fecha, tmp.id_trabajador
, tmd.inicio, tmd.termino
, COALESCE(CAST(tmd.jornada AS varchar(20)), 'DESCANSO') jornada
FROM (SELECT * FROM shift_cmr..fnRangoFechas('01-sep-2021', '31-dec-2021') t
CROSS JOIN (SELECT id_trabajador
FROM shift_cmr..trabajadores_turnos_planificados
WHERE fecha BETWEEN '2021-09-01' AND '2021-12-31'
GROUP BY id_trabajador) tt
) tmp
LEFT JOIN (SELECT *
FROM shift_cmr..trabajadores_turnos_planificados
WHERE fecha BETWEEN '2021-09-01' AND '2021-12-31') tmd
ON tmp.fecha = tmd.fecha
AND tmp.id_trabajador = tmd.id_trabajador
You need to start with the date table and LEFT JOIN everything else
SELECT
dates.fecha,
sh.id_trabajador,
sh.inicio,
sh.termino,
jornada = ISNULL(CAST(sh.jornada AS varchar(10)), 'DESCANSO')
FROM shift_cmr..fnRangoFechas('01-sep-2021', '31-dec-2021') dates
LEFT JOIN shift_cmr..trabajadores_turnos_planificados sh
ON sh.fecha = dates.fecha
This only gives you one blank row per date. If you need a blank row for every id_trabajador then you need to cross join that
SELECT
dates.fecha,
t.id_trabajador,
sh.inicio,
sh.termino,
jornada = ISNULL(CAST(sh.jornada AS varchar(10)), 'DESCANSO')
FROM shift_cmr..fnRangoFechas('01-sep-2021', '31-dec-2021') dates
CROSS JOIN shift_cmr..trabajadores t -- guessing the table name
LEFT JOIN shift_cmr..trabajadores_turnos_planificados sh
ON sh.fecha = dates.fecha AND t.id_trabajador = sh.id_trabajador

Is there a way to limit a sum up to a calculated date in a table?

I have a table with SentDate and RefundAmounts. I would like to sum up the amounts on each row from the date until a year into the future for every line.
In the example below I would like to add a column that says sum for the year.
This sum should be for the first line the sum of refunds from '2006-12-14' until '2007-12-14' which would be 3696,22 as there were no refunds during that period.
The second row would be from '2007-12-24' until '2008-12-24' which would be 463,05
SentDate YearAhead RefundAmount
2006-12-14 2007-12-14 3696,22
2007-12-24 2008-12-24 394,35
2008-12-18 2009-12-18 44,33
2008-12-19 2009-12-19 24,37
2009-12-16 2010-12-16 21,88
I have tried something along the lines of
select SentDate, dateadd(year,1,sentdate) YearAhead, SumRefund
from table
but I have no idea how to get the annual future sum for each row
Thanks for the suggestion. The final result should look as follows:
SentDate YearAhead RefundAmount SumForYear
2006/12/14 2007/12/14 3696,22 3696,22
2007/12/24 2008/12/24 394,35 463,05
2008/12/18 2009/12/18 44,33 90,58
2008/12/19 2009/12/19 24,37 46,25
2009/12/16 2010/12/16 21,88 21,88
You need to join with a BETWEEN to gather all rows that compose that period, then use GROUP BY with SUM to the result.
select
T.SentDate,
dateadd(year, 1, T.SentDate) YearAhead,
SUM(P.SumRefund) AS TotalOverYear
from
YourTable AS T
INNER JOIN YourTable AS P ON P.SentDate BETWEEN T.SendDate AND DATEADD(YEAR, 1, T.SendDate)
GROUP BY
T.SentDate
Something like this should suite your needs if you always need a complete year:
select sum(refund) as refundAmounts,year(min(SentDate)) as year from yourTable group by year(SentDate)
the year function gets only the year part from a datetime row and with group by you can split the aggregation of sum and min function to different groups.

How to list records with conditional values and non-missing records

I have a view that produces the result shown in the image below. I need help with the logic.
Requirement:
List of all employees who achieved no less than 100% target in ALL Quarters in past two years.
"B" received 90% in two different quarters. An employee who received less than 100% should NOT be listed.
Notice that "A" didn't work for Q2-2016. An employee who didn't work for that quarter should NOT be listed.
"C" is the only one who worked full two years, and received 100% in each quarter.
Edit: added image link showing Employee name,Quarter, Year, and the score.
https://i.imgur.com/FIXR0YF.png
The logic is pretty easy, it's math with quarters that is a bit of a pain.
There are 8 quarters in the last two years, so you simply need to select all the employee names in the last two years with a target >= 100%, group by employee name, and apply a HAVING clause to limit the output to those employees with count(*) = 8.
To get the current year and quarter, you can use these expressions:
cast(extract('year' from current_date) as integer) as yr,
(cast(extract('month' from current_date) as integer)-1) / 3 + 1 as quarter;
Subtract 2 from the current year to find the previous year and quarter. The code will be clearer if you put these expressions in a subquery because you will need them multiple times for the quarter arithmetic. To do the quarter arithmetic you must extract the integer value of the quarter from the text values you have stored.
Altogether, the solution should look something like this:
select
employee
from
(select employee, cast(right(quarter,1) as integer) as qtr, year
from your_table
where target >= 100
) as tgt
cross join (
select
cast(extract('year' from current_date) as integer) as yr,
(cast(extract('month' from current_date) as integer)-1) / 3 + 1 as quarter
) as qtr
where
tgt.year between qtr.yr-1 and qtr.yr
or (tgt.year = qtr.yr - 2 and tgt.qtr > qtr.quarter)
group by
employee
having
count(*) = 8;
This is untested.
If you happen to be using Postgres and expect to be doing a lot of quarter arithmetic you may want to define a custom data type as described in A Year and Quarter Data Type for PostgreSQL

Progress date comparision

I am trying to make a query in Progress. I should select all records older than exactly one year, so the current date minus 1 year. I have tried several possibilities but became every time an error. The query belongs to a join and should take every record of the previous year up to the current date minus one year:
left outer join data.pub."vc-669" as det2
on deb.cddeb = det2.cddeb
and det2.jaar = year(curdate()) - 1
and det2."sys-date" < date(month(curdate()), day(curdate()), year(curdate()) - 1)
That should simply be:
and det2."sys-date" < add-interval( curdate(), - 1, 'year' )
(As this already deals with the year, there is no need to look at det2.jaar, too.)
https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvref/add-interval-function.html

Confused on count(*) and self joins

I want to return all application dates for the current month and for the current year. This must be simple, however I can not figure it out. I know I have 2 dates for the current month and 90 dates for the current year. Right, Left, Outer, Inner I have tried them all, just throwing code at the wall trying to see what will stick and none of it works. I either get 2 for both columns or 180 for both columns. Here is my latest select statement.
SELECT count(a.evdtApplication) AS monthApplicationEntered,
count (b.evdtApplication) AS yearApplicationEntered
FROM tblEventDates a
RIGHT OUTER JOIN tblEventDates b ON a.LOANid = b.loanid
WHERE datediff(mm,a.evdtApplication,getdate()) = 0
AND datediff(yy,a.evdtApplication, getdate()) = 0
AND datediff(yy,b.evdtApplication,getdate()) = 0
You don't need any joins at all.
You want to count the loanID column from tblEventDates, and you want to do it conditionally based on the date matching the current month or the current year.
SO:
SELECT SUM( CASE WHEN Month(a.evdtApplication) = MONTH(GEtDate() THEN 1 END) as monthTotal,
count(*)
FROM tblEventDates a
WHERE a.evdtApplication BETWEEN '2008-01-01' AND '2008-12-31'
What that does is select all the event dates this year, and add up the ones which match your conditions. If it doesn't match the current month it won't add 1. Actually, don't even need to do a condition for the year because you're just querying everything for that year.