I'm trying to create a system that will select the old users that have not logged in for the past 7 days. I have a problem with this query.
The query should select the a.email, p.name, a.name, b.account_id, and I'll explain.
a is accounts
b is billing
p is players
Should check if the b.account_id is equal a.id that can get by p.account_id and after that should check if the p.lastlogin is higher or equal than 7 days then should return the query results.
I tried this, but it isn't working:
SELECT
`p`.`name`,
`a`.`email`,
`a`.`name`,
`b`.`account_id`
FROM
`billing` AS `b` AND `players` AS `p`
LEFT JOIN `accounts` AS `a`
ON `a`.`id` = `p`.`account_id` AND `a`.`name` = `b`.`account_id`
WHERE `p`.`lastlogin` >= UNIX_TIMESTAMP() + (7 * 86400)
AND group_id = 1
ORDER BY lastlogin
DESC
I hope that this is understandable, xD.
Regards,
vankk.
I think the problem is here.
WHERE `p`.`lastlogin` >= UNIX_TIMESTAMP() + (7 * 86400)
It should be -instead of +.
Also, why don't you use 2 JOINs?
You can also use the DATEDIFF function if you are using SQL
where DATEDIFF(d, a.DateValue , DateTimeNow) <7;
https://www.w3schools.com/sql/func_datediff.asp
Related
I am trying to make a Calculation where I want to update ideal hours based on number of Assistant and Head Coaches based on whether a restaurant is 5 day or 7 day a week. When I make a calculation where I use 10/7 or 20/7, it takes it as 1 and 2 respectively. I am currently using trunc but I have tried using cast :: decimal(10,6) etc and it doesn't work.
select
a.entity,
a.store_name,
a.order_date,
a.daily_ideal_hours,
a.daily_ideal_hours - (case when b.days_open like '%Weekdays%' then ((c.total_acs*(20/5) + c.total_hcs*(10/5)))
when b.days_open like '%All%' then ((c.total_acs * trunc(20/7,10)) + (c.total_hcs * trunc(10/7,10))) end) as updated_value
from scorecards_ideal_labor_hours as a
left join days_store_open as b
on a.entity = b.entity
left join hc_ac_data as c
on a.entity = c.entity_id
and a.order_date = c.report_date
where a.order_date between '2021-12-06' and '2021-12-12'
and a.entity = 66
order by a.order_date desc;
How do I fix this?
You don't need to use trunc function here.
Just typecast both numerator and denominator to float.
This will give the final answer with decimal places, without any rounding:
select (10::float)/(7::float);
This gives answer as:
1.4285714285714286
If you need to round the final answer to few digits only:
select trunc((10::float)/(7::float),2);
I have two tables.
Table 1 = My Trades
Table 2 = Market Trades
I want query the market trade 1 minute prior to my trade. If there is no market trade in Table 2 that is 1 minute apart from mine then I want to look back 2 minutes and so on till I have a match.
Right now my query gets me 1 minute apart but I cant figure out how to get 2 minutes apart if NULL or 3 minutes apart if NULL (up to 30 minutes). I think it would best using a variable but im not sure the best way to approach this.
Select
A.Ticker
,a.date_time
,CONVERT(CHAR(16),a.date_time - '00:01',120) AS '1MINCHANGE'
,A.Price
,B.Date_time
,B.Price
FROM
Trade..MyTrade as A
LEFT JOIN Trade..Market as B
on (a.ticker = b.ticker)
and (CONVERT(CHAR(16),a.date_time - '00:01',120) = b.Date_time)
There is no great way to do this in MySQL. But, because your code looks like SQL Server, I'll show that solution here, using APPLY:
select t.Ticker ,
convert(CHAR(16), t.date_time - '00:01', 120) AS '1MINCHANGE',
t.Price,
m.Date_time,
m.Price
from Trade..MyTrade as t outer apply
(select top 1 m.*
from Trade..Market m
where a.ticker = b.ticker and
convert(CHAR(16), t.date_time - '00:01', 120) >= b.Date_time)
order by m.DateTime desc
) m;
I have query resulting me 1 column of strings, result example:
NAME:
-----
SOF
OTP
OTP
OTP
SOF
VIL
OTP
SOF
GGG
I want to be able to get SOF, OTP, VIL - the first 3 unique top,
I tried using DISTINCT and GROUP BY, but it is not working, the sorting is damaged..
The query building this result is :
SELECT DISTINCT d.adst
FROM (SELECT a.date adate,
b.date bdate,
a.price + b.price total,
( b.date - a.date ) days,
a.dst adst
FROM flights a
JOIN flights b
ON a.dst = b.dst
ORDER BY total) d
I have "flights" table with details, and I need to get the 3 (=n) cheapest destinations.
Thanks
This can easily be done using window functions:
select *
from (
SELECT a.date as adate,
b.date as bdate,
a.price + b.price as total,
dense_rank() over (order by a.price + b.price) as rnk,
b.date - a.date as days,
a.dst as adst
FROM flights a
JOIN flights b ON a.dst = b.dst
) t
where rnk <= 3
order by rnk;
More details on window functions can be found in the manual:
http://www.postgresql.org/docs/current/static/tutorial-window.html
Find a way to do it.
I am selecting the DST and the PRICE, grouping by DST with MIN function on Price and limiting 3.
do I have better way to do it?
SELECT d.adst , min(d.total) mttl
FROM (SELECT a.date adate,
b.date bdate,
a.price + b.price total,
( b.date - a.date ) days,
a.dst adst
FROM flights a
JOIN flights b
ON a.dst = b.dst
ORDER BY total) d
group by adst order by mttl;
select
name
from
testname
where
name in (
select distinct(name) from testname)
group by name order by min(ctid) limit 3
SQLFIDDLE DEMO
You can tweak your query to return the correct result, by adding where days > 0 and limit 3 in the outer query like this:
select *
from
(
select
a.date adate,
b.date bdate,
(a.price + b.price) total,
(b.date - a.date) days ,
a.dst adst
from flights a
join flights b on a.dst = b.dst
order by total
) d
where days > 0
limit 3;
SQL Fiddle Demo
This assuming that the second entry is the return flight with date greater than the first entry. So that you got positive days difference.
Note that, your query without days > 0 will give you a cross join between the table and it self, for each flight you will get 4 rows, two with it self with days = 0 and other row with negative days so I used days > 0 to get the correct row.
I recommend that you add a new column, an Id Flight_Id as a primary key, and another foreign key something like From_Flight_Id. So the primary flight would have a null From_Flight_Id, and the returning flight will have a From_Flight_Id equal to the flight_id of the primary filght, this way you can join them properly instead.
SELECT DISTINCT(`EnteredOn`) FROM `rm_pr_patients` Group By `EnteredOn`
SELECT DISTINCT ON (column_name) FROM table_name order by name LIMIT 3;
I have an interesting problem and am unsure how to write a query to solve it. Say I have a table named "Cars". It has two columns, CarId (int PK), and ArrivalTime (datetime). As cars enter a space, the arrival time is entered.
What I need to know is this: for each car, how many entered the space in the 24 time period prior to it's arrival.
I'd like to write this without using a cursor, but don't know how I can do it. Any SQL gurus out there with an idea?
Oh - I should mention that the SQL Server version being used is 2005.
You could use a query with either a correlated subquery or a join.
Here's an example of query using a join operation:
SELECT n.CarId
, n.ArrivalDate
, COUNT(p.CarId) AS cnt_previous_arrivals
FROM cars n
LEFT
JOIN cars p
ON p.CarId = n.CarId
AND p.ArrivalDate >= DATEADD(HOUR,-24,n.ArrivalDate)
AND p.ArrivalDate < n.ArrivalDate
GROUP
BY n.CarId
, n.ArrivalDate
To get an equivalent result with correlated subquery, one option:
SELECT n.CarId
, n.ArrivalDate
, ( SELECT SUM(1)
FROM cars p
WHERE p.CarId = n.CarId
AND p.ArrivalDate >= DATEADD(HOUR,-24,n.ArrivalDate)
AND p.ArrivalDate < n.ArrivalDate
) AS cnt_previous_arrivals
FROM cars n
ORDER
BY n.CarId
, n.ArrivalDate
select el1.car_id,
( select count(*)
from entry_log el2
where el2.datetime between DATEADD(day, -1, el1.datetime)
and el1.datetime
and el2.car_id != el1. car_id
)
from entry_log el1
where el1.car_id = :my_car_id
Im trying to get sum of points for a user in the last month and the total, is it possible to get it in one query? Im using zend but i can probably get it working with provided sql.
heres my total for last month
$select = $this->_db
->select()
->from(array('p' => $this->_name), array(
'user_login',
'sum' => new Zend_Db_Expr('SUM(p.value)'),
)
)
->joinLeft(array('u' => 'user'), 'p.user_login = u.login')
->group('p.user_login')
->where('DATE(when) >= CURDATE() - INTERVAL 30 DAY')
->order('sum DESC')
;
return $this->getAdapter()->fetchAll($select);
As I understand the question, you want to show the total for the last 30 days and the total of all times for each user; sadly I can't test the Zend syntax and I'm not very used to it, but here is one version of the required SQL for MySQL;
SELECT p.user_login,
SUM(IF(DATE(`when`) >= CURDATE() - INTERVAL 30 DAY,p.value,0)) sum,
SUM(p.value) total_sum
FROM user_value p
JOIN user u
ON u.login = p.user_login
GROUP BY p.user_login
ORDER BY sum DESC;
SQLfiddle for testing.
I believe your initial query is equivalent to this SQL:
SELECT p.user_login, SUM(p.value) as sum_last_month
FROM person p
LEFT JOIN user u ON p.user_login = u.login
WHERE DATE(when) >= CURDATE() - INTERVAL 30 DAY
GROUP BY p.user_login
ORDER BY sum_last_month DESC
I'm not sure how to do a nested SELECT like this with Zend, but in SQL I believe something like this would work:
SELECT p.user_login, SUM(p.value) as sum_last_month,
(SELECT SUM(p2.value) FROM person p2 WHERE p2.id = p.id) as total
FROM person p
LEFT JOIN user u ON p.user_login = u.login
WHERE DATE(when) >= CURDATE() - INTERVAL 30 DAY
GROUP BY p.user_login
ORDER BY sum_last_month DESC, total DESC