But I can’t extract two random days from month and year from my MySQL table
On this table, I have stored all days from each month of the year and for each row it’s stored the login of users
I need random extracting, e.g.
All rows of the day 2023-10-29 and all rows of the day 2023-10-03 or all rows of the day 2023-10-18 and all rows of the day 2023-10-14, excluding all other days of the month
SELECT *
FROM _tbl_login
WHERE _Date IN
( SELECT _Date
FROM _tbl_login
GROUP
BY _Date
ORDER
BY RAND() LIMIT 2 );
> 1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
> Time: 0,078s
WITH rando AS
( SELECT _Date
, ROW_NUMBER()
OVER(ORDER BY RAND() ) AS rn
FROM _tbl_login )
SELECT *
FROM _tbl_login
WHERE _Date IN
( SELECT _Date
FROM rando
WHERE rn <= 2 )
I have tried this query, but on the return I have all days and all rows of October month from the table _tbl_login…
I need only two days from the table _tbl_login of October month
WITH rando AS
( SELECT ` _Date`,
ROW_NUMBER()
OVER ( PARTITION BY ` _Date` ORDER BY RAND() ) AS rn
FROM _tbl_login WHERE MONTH ( _Date ) = '10' )
SELECT * FROM
_tbl_login
WHERE
` _Date` IN ( SELECT ` _Date` FROM rando WHERE rn <= 2 )
AND MONTH ( _Date ) = '10';
WITH dates AS
( SELECT DISTINCT
_Date
FROM _tbl_login
WHERE _Date >= '2023-10-01'
AND _Date < '2023-11-01' )
, rando AS
( SELECT _Date
, ROW_NUMBER()
OVER(ORDER BY RAND()) AS rn
FROM dates )
SELECT *
FROM rando
WHERE rn <= 2
WITH dates AS
( SELECT DISTINCT
_Date
FROM _tbl_login
WHERE _Date >= '2023-10-01'
AND _Date < '2023-11-01' )
, rando AS
( SELECT _Date
, ROW_NUMBER()
OVER(ORDER BY RAND()) AS rn
FROM dates )
SELECT *
FROM _tbl_login
WHERE _Date IN
( SELECT _Date
FROM rando
WHERE rn <= 2 )
mysql> WITH dates AS
( SELECT DISTINCT
_Date
FROM _tbl_login
WHERE _Date >= '2023-10-01'
AND _Date < '2023-11-01' )
, rando AS
( SELECT _Date
, ROW_NUMBER()
OVER(ORDER BY RAND()) AS rn
FROM dates )
SELECT _Date
FROM _tbl_login
WHERE _Date IN
( SELECT _Date
FROM rando
WHERE rn <= 2 );
+-------------------------+
| _Date |
+-------------------------+
| 2023-10-25 |
| 2023-10-16 |
+-------------------------+
2 rows in set (0.34 sec)
okay, considering my batting average on this one, i am going to stop writing wild queries and ask that you prepare a fiddle so that i can test my queries against your data
feel free to use SQL Fiddle or DB Fiddle, and it won’t matter which dbms you choose, as i believe they all support CTEs, which is all we need here