Find the last 10 days from today and query in Google Sheets - sorting

I have this sheet here set in a tab named Reports:
As can be seen, column A contains the date and time of the report. The most recent has been set on February 16th and the oldest is January 28th.
I would like to query the last 10 days, starting from today in another tab. So, if today is February 17th, I need all the reportes queried until February 7th.
Note: I don't need the last 10 reports, I need the last 10 days, no matter how many is accumulated.
I tried something like this:
=QUERY(SORT({
'Reports'!A1:A;
}, 1, 0),
"where Col2 is not null limit 10", 0)
Here is the sheet:
https://docs.google.com/spreadsheets/d/1w7beVyUr0pEUoRSgqQYYOi0y0Sbd8scC3B825GKA3sQ/edit?usp=sharing

Try this:
=QUERY({Report!A1:B} ; "SELECT *
WHERE Col2 is not null AND Col1 >= date '"
& TEXT(NOW()-10; "yyyy-MM-dd") & "' ")

try:
=QUERY({Report!A1:B};
"where Col1 >= date '"&TEXT(TODAY()-10; "yyyy-mm-dd")&"'
and Col1 <= date '"&TEXT(TODAY(); "yyyy-mm-dd")&"'"; 0)
or from Control sheet:
=ARRAYFORMULA(QUERY({IFNA(IF(N(Control!A2:A)<>0; Control!A2:A; DATE(
REGEXEXTRACT(Control!A2:A; "/(\d+) ");
REGEXEXTRACT(Control!A2:A; "/(\d+)/");
REGEXEXTRACT(Control!A2:A; "^\d+"))+
INDEX(SPLIT(Control!A2:A; " ");;2)))\ Control!B2:B};
"where Col1 >= "&DATEVALUE(TODAY()-10)&"
and Col1 <= "&DATEVALUE(TODAY())&"
format Col1 'mm/dd/yyyy hh:MM:ss'"; 0))

Related

Query importrange within date parameters and separate time parameters returning percentage

I have created this formula that should count all rows from another sheet with the specific mentioned value with date range => & =< and with time range => & =<
It returns 0 regardless of what values I test with...
=COUNTA(IFERROR(QUERY({IMPORTRANGE("/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit#gid=431567503", "July!A2:C")},
"Select Col1 where Col1 contains '"&A3&"'
and Col2 >= date '2022-07-01'
and Col2 <= date '2022-07-31'
and Col3 >= time '18:00'
and Col3 <= time '08:00'" ,0)))
Data:
https://docs.google.com/spreadsheets/d/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit#gid=431567503
Testing sheet:
https://docs.google.com/spreadsheets/d/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit#gid=1075801741
In the ideal world I would want to take this a step further and instead of a count of this data it would return a percentage of all the data based on the partner name in Sheet2! '"&A3&"'
Update
1 step closer:
=COUNTA(IFERROR(QUERY({IMPORTRANGE("/1xNFVHLnQGkRgZdLmejCyU0BByOPBY8NMoIYj6SkTFGY/edit#gid=431567503", "July!A2:D")},
"Select Col1 where Col1 contains '"&A3&"'
and Col4 >= datetime '"&TEXT(H1,"e-MM-dd HH:mm:ss")&"'
and Col4 <= datetime '"&TEXT(H2,"e-MM-dd HH:mm:ss")&"'",0)))
This formula returns data that is within a specific time and date range and has a particular value in a column.
The way I worded the original question would mean I am now almost there.
there is no time. go for datetime:
update:
D2:
=ARRAYFORMULA(IF(A2:A="",,B2:B+C2:C))
G4:
=COUNTA(IFERROR(QUERY({IMPORTRANGE(
"1WsQQJ3qWM_m-nHW6R4xhewgQTfN5haZ61eJx1KkgaSg", "July!A2:D")},
"select Col1
where Col4 >= datetime '"&TEXT(H1, "e-MM-dd HH:mm:ss")&"'
and Col4 <= datetime '"&TEXT(H2, "e-MM-dd HH:mm:ss")&"'", 0)))
demo sheet

oracle - how to order by with date in the format dd-MMM-yy

I am able to select records and all like in the query below but select statement is picking records randomly that were create after the specified date. I am curious if there is a way to order by this date in the format dd-MMM-yy like 05-MAY-21..
select * from Employees
where createDt >= '05-MAY-21'
order by CreateDt asc
This statement is not giving what I am hoping for, which is start with records from date 05, 06, etc..
thank you in advance.
date in the format dd-MMM-yy like 05-MAY-21
A DATE is a binary data-type and it does NOT have any format.
If you do:
select *
from Employees
where createDt >= DATE '2021-05-05'
order by CreateDt asc
Then it will sort the dates in ascending order by year then by month and then by day and then by hour and then by minute and then by second (yes, a DATE always has a time component).
If you do:
select *
from Employees
where createDt >= '05-MAY-21'
order by CreateDt asc
Then you are implicitly asking Oracle to convert the string to a DATE and your query is actually doing:
select *
from Employees
where createDt >= TO_DATE(
'05-MAY-21',
( SELECT value
FROM NLS_SESSION_PARAMETERS
WHERE parameter = 'NLS_DATE_FORMAT' )
)
order by CreateDt asc
If the NLS_DATE_FORMAT session parameter does not match the format of your string then you will get unexpected results.
If you want to order the dates alphabetically, rather than chronologically then convert them to a string in the ORDER BY clause:
select *
from Employees
where createDt >= DATE '2021-05-05'
order by TO_CHAR(CreateDt, 'DD-MON-YY') asc
However, I'm not sure hy you would want to do this.
WHERE clause seems to be wrong.
You said that createDt column's datatype is DATE. So, why are you comparing it to a string? Use date literal or TO_DATE function, don't rely on implicit datatype conversion.
select * from Employees
where createDt >= date '2021-05-05' -- No! '05-MAY-21'
order by CreateDt asc
If, on the other hand, you only think that column's datatype is DATE but is - actually - VARCHAR2, then you'll have to "convert" it to a valid date value using TO_DATE function with appropriate date format mask, hoping that all values in that column have the same, valid format:
select * from Employees
where to_date(createDt, 'dd-mmm-yy', 'nls_date_language = english') >= date '2021-05-05'
order by to_date(createDt, 'dd-mmm-yy', 'nls_date_language = english') asc
If none of above helps, please, post some sample data. That includes CREATE TABLE and INSERT INTO several sample rows.
It would really help if you showed what results you're getting and what are your desired results...
Anyway, I'm trying to guess basing on the question and your comments
Let's start with "... statement is picking records randomly ..."
and "This statement is not giving what I am hoping for, which is start with records from date 05, 06, etc.."
and later: "and the order in which the records are weird.. like dates in the order of 08, 11, 12, 24, 24, 27, 27, 31, etc "
OK, the order "08, 11, 12, 24, 24, 27, 27, 31, etc." does not seem random, does it? It is pretty much the order you requested - ascending.
I'm guessing that all those dates are in may, so you really are getting what you requested for: records from Employees table with createDt greater or equal to 5th of may and sorted in ascending order.
But you are saying that the dates order seems weird to you, you were expecting 05, 06, ..., and you got 08, 11, 12, 24
Oh! What seems to be bothering you is the fact that you have some gaps between the dates and that the dates do not start with May 5th. Is that it? Well, then, simple answer is: those dates are simply not present in the Employees table.
You ask elsewhere ".. how do I limit that to send only 10 records?"
Ok, so let me guess what you would like to get.
You would like to see 10 consecutive dates starting with may 5th and the records which were created for each date.
In that case you have to "generate" those dates and then join them with your Employees table taking into account that for some of the dates you will have no row - hence LEFT JOIN.
with dates as
(select date '2021-05-05' + (level - 1) d from dual connect by level <= 10)
select e.*
from dates d
left join employees e
on e.createDt = d.d
order by d.d
or, if the createDt contains time component
with dates as
(select date '2021-05-05' + (level - 1) d from dual connect by level <= 10)
select e.*
from dates d
left join employees e
on e.createDt >= d.d and e.createDt < d.d + 1
order by d.d, e.createDt
I'm not sure if this is it, though
Also: you may use the literal '05-MAY-21' but only if you are absolutely sure that your session uses this exact date format. It's safer to use the datetime literal or to_date function ( to_date('05-MAY-21', 'DD-MON-YY') )

Oracle sql how to get the date of a week

I have the following query that gets the week of a date:
SELECT pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww') semana,
SUM (rta.kms_acumulados) kms,
COUNT
(DISTINCT (CASE
WHEN v.secuencia BETWEEN rta.sec_origen AND rta.sec_destino
THEN v.cod_inc
ELSE '0'
END
)
)
- 1 numincidencias
FROM (SELECT ms.tren, ms.fecha_origen_tren, ms.secuencia, ri.cod_inc
FROM r_incidencias ri, mer_sitra ms
WHERE ri.cod_serv = ms.tren
AND ri.fecha_origen_tren = ms.fecha_origen_tren
AND ri.cod_tipoin IN (SELECT cod_tipo_iincidencia
FROM v_tipos_incidencias
WHERE grupo = '45')
AND ri.punto_desde = ms.cod_estacion) v,
r_trenes_asignar rta,
r_maquinas rm,
planificador.pl_dh_material pdm
WHERE rta.fecha BETWEEN TO_DATE ('21/09/2018', 'dd/mm/yyyy') AND TO_DATE ('21/09/2018',
'dd/mm/yyyy'
)
AND rta.serie >= 4000
AND rta.matricula_ant IS NOT NULL
AND rm.matricula_maq = rta.matricula_ant
AND rm.cod_serie = pdm.id_material
AND rta.grafico BETWEEN pdm.desde AND pdm.hasta
AND v.tren(+) = rta.tren
AND v.fecha_origen_tren(+) = rta.fecha
GROUP BY pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww')
ORDER BY pdm.serie, rta.matricula_ant, TO_CHAR (fecha, 'ww')
For example week 1
I want to display
week 1 : 1 january - 7 january
How can I get this?
Oracle offers the TRUNC(datestamp, format) function to manipulate dates this way. You may use a variety of format strings to get the first day of a quarter, year, or even the top of the hour.
Given a particular datestamp value, Oracle returns midnight on the first day of the present week with this expression:
TRUNC(datestamp,'DY')
You can add days to a datestamp. Therefore this expression gives you midnight on the last day of the week
TRUNC(datestamp,'DY') + 6
A WHERE-clause selector for all rows in the present week might be this.
WHERE datestamp >= TRUNC(SYSDATE,'DY')
AND datestamp < TRUNC(SYSDATE,'DY') + 7
Notice that the end of the range is just before (<) midnight on the first day of the next week. You need that because you may have datestamps after midnight on the last day of the week. (Beware using BETWEEN for datestamp ranges.)
And,
SELECT TO_CHAR(TRUNC(SYSDATE,'DY'),'YYYY-MM-DD'),
TO_CHAR(TRUNC(SYSDATE,'DY')+6,'YYYY-MM-DD')
FROM DUAL;
displays the first and last dates of the present week in ISO-like format.
Date arithmetic is cool. It's worth your trouble to study the date-arithmetic functions in your DBMS at least once a year.

Comparison between day of week in oracle

I have problems with comparing the day of week
Here is my query in oracle database.
SELECT DAY, WEEKDAY
FROM (SELECT v.TNI, v.FRMP, v.LR, v.DAY, v.HH, v.VOLUME,
CASE WHEN hd.HOLIDAY_DATE is not null then 'HOLIDAY'
ELSE to_char(v.DAY, 'Day') END AS WEEKDAY
FROM v_nem_rm16 v
LEFT JOIN DBP_ADMIN.DBP_HOLIDAY hd
ON v.DAY = hd.HOLIDAY_DATE
WHERE v.STATEMENT_TYPE != 'FORECAST')
WHERE WEEKDAY = 'Monday';
Basically, the "WEEKDAY" column has the day of week based on the "DAY". Day is just date like 13/Mar/17
If you look at the "CASE" statement, you will notice that the "WEEKDAY" column is filled by "to_char(v.DAY, 'Day')".
So the column has values like "Sunday, Saturday and so on, the day of week".
The problem is the outer query's where clause, "WHERE WEEKDAY = 'Monday'"
When I execute this query, It does not give me any rows even if I have rows having Monday as the value in "WEEKDAY" column
But when I change the WHERE clause to "WHERE WEEKDAY = to_char(sysdate, 'Day')", It works fine. The sql statement gives me the rows having "Saturday" in "WEEKDAY" column since the "to_char(sysdate, 'Day')" gives me "Saturday".
So what is problems with my first query??
I just want to filter rows by the name of the day of week like if i pass "Monday", i want to have all the rows having " Monday" in "WEEKDAY" column.
How can I do??
THANKS GUYS
It appears TO_CHAR(, 'Day') returns a fixed length string with right side padding of blanks. So, you are not getting 'Monday', you are really getting 'Monday '. The longest day is 'Wednesday', so it is a 9 character string. So, either trim the value or compare against 'Monday ' exactly.
select '|'||to_char(sysdate+level,'Day') ||'|' days_of_the_week
from dual
connect by level <= 7;
Results...
|Saturday |
|Sunday |
|Monday |
|Tuesday |
|Wednesday|
|Thursday |
|Friday |
if you would like to use the day names (either full or abbreviated), I suggest to specify the language in the to_char function as follows:
select '|'||to_char(sysdate+level, 'fmDay', 'NLS_DATE_LANGUAGE = American') ||'|' days_of_the_week_enu,
'|'||to_char(sysdate+level, 'fmDay', 'NLS_DATE_LANGUAGE = German') ||'|' days_of_the_week_ger,
'|'||to_char(sysdate+level, 'DY', 'NLS_DATE_LANGUAGE = American') ||'|' days_of_the_week_abbr_enu,
'|'||to_char(sysdate+level, 'DY', 'NLS_DATE_LANGUAGE = German') ||'|' days_of_the_week_abbr_ger
from dual
connect by level <= 7;
This way the returned day names will be independent of session locale settings.
Result:

How to get one record before start date and end date

I want to get one record before start date and end date
DtpFrom means – 'date picker from
DtpTo means – 'date picker to
VB 6 CODE
sdate = DateToString(dtpFrom)
edate = DateToString(dtpTo)
QUERY
Where DATE BETWEEN '" & sdate & "' AND '" & edate & "'"
I want to get one record before sdate and edate
I tried this code
VB 6 CODE
s1sdate = -sdate
e1edate= -edate
QUERY
Where DATE BETWEEN '" & s1date & "' AND '" & e1date & "'"
But it is going one day minus
Example
Selecting 03/05/2009 to 03/06/2009 from date picker, but it showing record from
02/05/2009 to 02/06/2009.
I want to display one record before from the selecting date and ending date, not one day before, because my table is not a continous date.
ADDITIONAL EXAMPLE:
If we have a table and rows [ ID(int) , Value(Money) ] and we have some rows in it
ID --Value
1------70
2------100
3------150
8------200
20-----250
45-----280
and we want to make Query that get each row ID, Value and the previous Row Value in which data appear as follow
ID --- Value ---Prev_Value
1 ----- 70 ---------- 0
2 ----- 100 -------- 70
3 ----- 150 -------- 100
8 ----- 200 -------- 150
20 ---- 250 -------- 200
45 ---- 280 -------- 250
i make the following query but i think it's so bad in performance in huge amount of data
select t1.id, t1.value, t2.value from table t1 inner join table t2 on t1.id = t2.id where t2.value = (select max(value) from table t where t.value< t1.value and t.id = t1.id ) and T1.value BETWEEN '" & sdate & "' AND '" & edate & "'
Need VB 6 CODE OR ACCESS QUERY HELP.
SELECT * FROM whatever
WHERE DATE < sdate
ORDER BY DATE DESC
LIMIT 1
I don't think end date really matters if you want "the one before the records between start and end date"
But if you want the record right before start date AND the record right before end date you could just repeat the above query with edate instead of sdate.
This is what the query actually means: Select every record with a DATE before this one (sdate). For all of those records, order them by DATE in a descending manner (DESC). Only return the first one (LIMIT 1).
Note: Some implementations vary. You may need to use TOP 1 after the word SELECT instead of LIMIT 1

Resources