Mysql use between, Unix Time Stamp [duplicate] - mysql

This question already has answers here:
Can you use an alias in the WHERE clause in mysql?
(5 answers)
Closed 4 years ago.
So i am trying to use Between Timestamp as follows , i have date stored as Unix time stamp and i am 1st trying to convert it, and then get all users between the said time.
SELECT
users.*,
DATE_FORMAT(
FROM_UNIXTIME(users.created),
'%Y %b %e '
) AS date_formatted
FROM
node
LEFT JOIN users
ON node.uid = users.uid
WHERE node.uid != 0
AND
(date_formatted BETWEEN '2017-06-30 00:00:00' AND '2018-06-30 00:00:00')
GROUP BY uid
But i am getting this error
Unknown column 'date_formatted' in 'where clause'

the issue, as mentioned in the comments, is that "date_formatted" is an alias of a result. it is not in the tables itself and therefore you can't call it within the WHERE statement. You can call it at the end of a query using a HAVING statement, but that would mean that the query has to first pull up a whole lot more data than you need. MYSQL does a whole lot of implicit casting when it comes to dates, so you can probably just use:
users.created BETWEEN '2017-06-30 00:00:00' AND '2018-06-30 00:00:00'
but if you don't want to risk it, you can apply the formatting/casting within the WHERE statement.

Related

How to simplify queries

How can I simplify this query? Can this query be simplified? I tried some
joins but the results were not the same as this query below. Please give me
some insights.
SELECT trafficbywebsite.`adwordsCampaignID`,
trafficbywebsite.adwordsAdGroupID, trafficbywebsite.adPlacementDomain,
trafficbywebsite.counts traffic, convertedtrafficbywebsite.counts
convertedclicks
FROM
(
SELECT `adwordsAdGroupID`, `adPlacementDomain`, COUNT(*) counts
FROM
(
SELECT GA_entrances.*
FROM
GA_entrances,
GA_conversions
WHERE
GA_entrances.clientId=GA_conversions.clientId
AND (eventLabel='myurl' OR eventLabel='myotherurl')
AND YEAR(GA_entrances.timestamp)>=2016
AND MONTH(GA_entrances.timestamp)>=6
AND YEAR(GA_conversions.timestamp)>=2016
AND MONTH(GA_conversions.timestamp)>=6
GROUP BY GA_entrances.clientId
) clickers
GROUP BY `adwordsAdGroupID`, `adPlacementDomain`
) convertedtrafficbywebsite
,(
SELECT `adwordsCampaignID`, `adwordsAdGroupID`, adPlacementDomain,
COUNT(*) counts
FROM
GA_entrances
WHERE
YEAR(timestamp)>=2016
AND MONTH(timestamp)>=6
GROUP BY `adwordsAdGroupID`, `adPlacementDomain`
) trafficbywebsite
WHERE
convertedtrafficbywebsite.counts>=(trafficbywebsite.counts/10)
ORDER BY traffic DESC
Without sample data it is difficult to be certain but it appears unlikely you can remove one of the subqueries. What you can do however is improve the way you flter for the dates. The thing to avoid is using functions on data to suit your filter criteria. For example you want data from 2016-06-01 onward, that is a single date, yet you are amending every row of data to match to a year and a month.
AND YEAR(GA_entrances.timestamp) >= 2016
AND MONTH(GA_entrances.timestamp) >= 6
AND YEAR(GA_conversions.timestamp) >= 2016
AND MONTH(GA_conversions.timestamp) >= 6
;
There is no need for all those functions, just compare to a single date:
AND GA_entrances.timestamp) >= '2016-06-01'
AND GA_conversions.timestamp >= '2016-06-01'
;
The other thing to avoid is using commas as a way to join tables. ANSI standard syntax for this 25+ years old. This is the antique way of joining:
FROM GA_entrances, GA_conversions
WHERE GA_entrances.clientId = GA_conversions.clientId
This is considered best practice:
GA_entrances.*
FROM GA_entrances
INNER JOIN GA_conversions ON GA_entrances.clientId = GA_conversions.clientId

Mysql Query data between date on joined table [duplicate]

This question already has answers here:
Convert from MySQL datetime to another format with PHP
(18 answers)
SQL date format convert? [dd.mm.yy to YYYY-MM-DD]
(3 answers)
Closed 5 years ago.
Am trying to query data from two joined tables with a date as criteria using the query below but it brings nothing, can someone please show me what I did wrong.
SELECT Journal_T.GL_ID as Akaunti
,coa_t.gl_name_vc
,SUM(Amount_NU) as YTD
FROM Journal_T
JOIN coa_t
ON journal_t.gl_id = coa_t.gl_id
WHERE CAST(date_dt AS DATE) BETWEEN '25/08/2017' AND '25/08/2017'
AND bs_category_vc='Rev'
GROUP BY coa_t.gl_name_vc
,Journal_T.GL_ID
ISO 8601 Date format would be '2017-08-26'. Try this query to see default Date format on your server:
select STR_TO_DATE("26/08/2017", '%d/%m/%Y')
Then you can convert it, for example to '%Y-%m-%d' format:
DATE_FORMAT(STR_TO_DATE("26/08/2017", '%d/%m/%Y'), '%Y-%m-%d')
I think you can try out this query :
SELECT Journal_T.GL_ID as Akaunti,coa_t.gl_name_vc,sum(Amount_NU) as YTD
FROM Journal_T
LEFT JOIN coa_t on journal_t.gl_id = coa_t.gl_id
WHERE DATE_FORMAT(date_dt,'%d-%m-%Y') BETWEEN '25/08/2017' AND '25/08/2017'
AND bs_category_vc='Rev'
GROUP by coa_t.gl_name_vc,Journal_T.GL_ID

Mysql Select with Dates and maybe Case when

im having a problem where i cant think of a solution, maybe im having a bad table-structure or i just dont know enough about mysql select commands to think of a good solution. Maybe you can help me out:
So i got a table that has a Column with the Date-format (yyyy-mm-dd) i wanted to select all upcoming dates so i did:
SELECT * WHERE date >= now.
This worked kinda well but i also got "dates" where only the year is entered (2014-00-00) i also wanted to select these but "now" is already bigger so i made another column with the year only and if the month, date or both arent known i will use 0000-00-00 and the Column "year" now i could select like this:
SELECT * WHERE date >= now AND year >=now(year)
Now all entrys with 0000-00-00 wont be selected. If i use OR the entrys from last year will be shown.
So thats my problem, is there any way i can change my table so i can have entries with only the year or only year and month and of course all together? I already considered get rid of the date-format and use simple INT with seperated columns for year, month and date. But i think i will have the same problem.
Sometimes i just want to do a capsuled select like
SELECT *
WHERE (date >= now AND year >= now(year))
OR date == "0000-00-00" (i know that this doesnt work)
If I understood your problem correctly, you could use this request:
WHERE (date >= now OR year > now(year))
There is probably a simpler way though, that would preserve your design, like initializing at January 1st (01-01) instead of 00-00
I think you can use this code:
$_SESSION['month'] = //set here your selected month
$_SESSION['year'] = //set here your selected year
SELECT * FROM table WHERE DATEPART(m,date) >= '".$_SESSION['month']."' AND DATEPART(yyyy,year) >= '".$_SESSION['year']."' AND date <> '0000-00-00'
Change your table structure format. Actually just allow for that field to have null value when not entered. By default it will be null then. You shouldn't be storing 0000-00-00 as a value for Date type field. I would rather leave it as null , or as suggested in some of previous answers, initialize it with some other date. It would be much easier to manipulate with database then.
the problem is that half of you write is not MySQL and your database schema is terrible...
You have the following problems:
column data date does not have the date data type.
To fix it, you need to add a cast to the select statement eg. cast(datecolumn as date)
select * from table where cast(datecolumn as date) >= '2014-01-10';
the way to use now date is using the now function.
select now(), date(now());
result> 2014-01-10 11:11:36, 2014-01-10
select * from table where cast(datecolumn as date) >= date(now());
Because your datecolumn is not a date (2014-00-00 is not a valid date), you need to use string manipulation to extract the year.
select substring('2014-01-01', 1,4)
result> 2014
select * from table where substring(datecolumn, 1,4) = year(now());
The comparassion operator is = and not ==
the select statement syntax looks like this (pay attention because you are missing the table in your statement)
select * from [Table] where [column] = condition ...
You probably need or instead of ands, therefore your query should look like this:
select * from FooTable where
cast(datecolumn as date) >= date(now())
or substring(datecolumn, 1,4) >= year(now())
or datecolumn = '0000-00-00'
You should use something like phpmyAdmin or mySQL workbench to test your sql queries before try to use them on php, java or whatever is your programing language.

MySQL select Display Zero when group by month or week [duplicate]

This question already has answers here:
Mysql to select month-wise record even if data not exist
(2 answers)
Closed 9 years ago.
I have a table with a column date and a column ID (to keep it simple). I am doing a query to count the total and group by week
SELECT MONTH(table1.Date_1st), YEAR(table1.Date_1st), COUNT(table1.Id)
FROM table1 as table1
WHERE Date_1st BETWEEN '2013-04-01' AND '2013-07-25'
GROUP BY WEEK(Date_1st)
the problem is there is no results on specific week the result is not taken into consideration. I already try ifnull(table1.Id,0)
Try ISNULL or other NULL SQL functions:
NULL functions
ISNULL returns a 0 if the value is null.

Mysql summary query with date range, multiple tables

Im running a sql query that is returning results between dates I have selected (2012-07-01 - 2012-08-01). I can tell from the values they are wrong though.
Im confused cause its not telling me I have a syntax error but the values returned are wrong.
The dates in my database are stored in the date column in the format YYYY-mm-dd.
SELECT `jockeys`.`JockeyInitials` AS `Initials`, `jockeys`.`JockeySurName` AS Lastname`,
COUNT(`runs`.`JockeysID`) AS 'Rides',
COUNT(CASE
WHEN `runs`.`Finish` = 1 THEN 1
ELSE NULL
END
) AS `Wins`,
SUM(`runs`.`StakeWon`) AS 'Winnings'
FROM runs
INNER JOIN jockeys ON runs.JockeysID = jockeys.JockeysID
INNER JOIN races ON runs.RacesID = races.RacesID
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` <= STR_TO_DATE('2012,08,01', '%Y,%m,%d')
GROUP BY `jockeys`.`JockeySurName`
ORDER BY `Wins` DESC`
It's hard to guess what the problem is from your question.
Are you looking to summarize all the races in July and the races on the first of August? That's a slightly strange date range.
You should try the following kind of date-range selection if you want to be more precise. You MUST use it if your races.RaceDate column is a DATETIME expression.
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` < STR_TO_DATE('2012,08,01', '%Y,%m,%d') + INTERVAL 1 DAY
This will pick up the July races and the races at any time on the first of August.
But, it's possible you're looking for just the July races. In that case you might try:
WHERE `races`.`RaceDate` >= STR_TO_DATE('2012,07,01', '%Y,%m,%d')
AND `races`.`RaceDate` < STR_TO_DATE('2012,07,01', '%Y,%m,%d') + INTERVAL 1 MONTH
That will pick up everything from midnight July 1, inclusive, to midnight August 1 exclusive.
Also, you're not using GROUP BY correctly. When you summarize, every column in your result set must either be a summary (SUM() or COUNT() or some other aggregate function) or mentioned in your GROUP BY clause. Some DBMSs enforce this. MySQL just rolls with it and gives strange results. Try this expression.
GROUP BY `jockeys`.`JockeyInitials`,`jockeys`.`JockeySurName`
My best guess is that the jocky surnames are not unique. Try changing the group by expression to:
group by `jockeys`.`JockeyInitials`, `jockeys`.`JockeySurName`
In general, it is bad practice to include columns in the SELECT clause of an aggregation query that are not included in the GROUP BY line. You can do this in MySQL (but not in other databases), because of a (mis)feature called Hidden Columns.