I need to get data from my table.
I want only the data of last 24 h , counting the occurrence, with max 60 last infos.
TABLE super_table
id username date_post
---------------------
11 james 111105487
10 luke 110105474
9 james 110105400
8 john 111105486
7 james 111100487
6 luke 110105174
5 john 110205474
I want something like this
james(3)
luke(2)
john(2)
Code:
<?php
$delay_search=strtotime("+1 day");
$max_user_get=60;
$sql_total = "
SELECT username,COUNT(*) as count
FROM super_table where date_post <'$delay_search'
GROUP BY username
ORDER BY id DESC LIMIT 0,$max_user_get;
";
$temp='';
$result_total = $conn->query($sql_total);
$nb_total=$result_total->num_rows;
while($row = $result_total->fetch_assoc())
{
$username=$row["username"];
$total_post=$row['count'];
/*Edit*/
$temp.='User :'.$username.'('.$total_post.')';
}
echo $temp;
?>
I want only the data of last 24 h
This can be done by from_unixtime to convert the int to date
FROM_UNIXTIME(date_post) > NOW() - INTERVAL 1 DAY
counting the occurrence, with max 60 last infos
limit 60
Final query:
select username,
count(*)
from super_table
where FROM_UNIXTIME(date_post) > NOW() - INTERVAL 1 DAY
group by username
order by count(*) desc
limit 60;
No need for
$delay_search=strtotime("+1 day");
$max_user_get=60;
Related
This has me a stummped...
If I have a this MySQL table:
UserId | Commission | Date Of Commission
1 | 200.00 | 2014-02-12
1 | 50.00 | 2014-04-01
2 | 10.00 | 2014-04-05
and I would like to display the Total Commission for a specific user per week starting from his/her first record, and display 0 for that range if there's no record.
how would I go about it?
Sample Output
UserId | Date Range | Total Commission
1 | 02/10/14 - 02/16/14 | 200.00
1 | 02/17/14 - 02/23/14 | 0.00
...
1 | 03/31/14 - 04/06/14 | 50.00
I'm not a seasoned coder so any help will be much appreciated.
Thanks!
Edit:
I have tried this:
SELECT IFNULL(SUM(Commisssion),0) Total ,DATE_SUB(`DateOfCommission`,INTERVAL 7 DAY)
AS RangStart,DATE_SUB(`DateOfCommission`,INTERVAL 1 DAY) AS RangeEnd
FROM `comms` WHERE `UserId` = '$UserID' GROUP BY DATE(`DateOfCommission`) DESC
but it starts the week with whatever date the first record was entered..
This is very tricky to accomplish. Here is what I managed to do with small modifications it should work they way it needs to be. I have done it for userid = 1 and this could be done for other users as well.
In the query I have 2 lines
where a.Date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
and
WHERE date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
The query will try to generate the list of dates using the min() date of transaction for the user till today. Instead of now() this could be used as max() date of transaction for the user as well.
select
t1.date_range,
coalesce(SUM(t1.Commission+t2.Commission), 0) AS Commission
from
(
select
a.Date as date,
concat(
DATE_ADD(a.Date, INTERVAL(1-DAYOFWEEK(a.Date)) +1 DAY),
' - ',
DATE_ADD(a.Date, INTERVAL(7- DAYOFWEEK(a.Date)) +1 DAY)
) as date_range,
'0' as Commission
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as date
from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) a
where a.Date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
)t1
left join
(
SELECT date ,
coalesce(SUM(Commission), 0) AS Commission
FROM transactions
WHERE date BETWEEN (select min(date) from transactions where UserId = 1) AND NOW()
AND UserId = 1
GROUP BY date
)t2
on t2.date = t1.date
group by t1.date_range
order by t1.date_range asc
DEMO
So, this is sort of an algorithm you could use:
$Result = select distinct userid from table(this will fetch all userids from table)
while(There are rows in $Result)
{
$Userid = $Result['userid']
$StartDateRes = mysql_query(select Date, WEEKOFYEAR(Date) as week from table where userid = Userid order by date asc limit 1)
$StartDateRow = mysql_fetch_assoc($StartDateRes)
$StartDate = $StartDateRes['Date']
$StartWeekNumber = $StartDateRes['week']
$EndDateRes = mysql_query(select Date, WEEKOFYEAR(Date) as week from table where userid = Userid order by date desc limit 1)
$EndDateRow = mysql_fetch_assoc($EndDateRes)
$EndDate = $EndDateRes['Date']
$EndWeekNumber = $EndWeekRes['week']
for($i=$StartWeekNumber; $i<=$EndWeekNumber; $i++)
{
$StartDateOfWeek = FuncToFindStartDateOfWeek($i)
$EndDateOfWeek = FuncToFindEndDateOfWeek($i)
$Result2 = mysql_query(select sum(commission) as sum from table where date between StartDateOfWeek and EndDateOfWeek group by userid)
$Row2= mysql_fetch_assoc($Result2)
$Sum = $Row2['sum']
mysql_query("insert into OutputTable values($UserId, $StartDateOfWeek. '-'. $EndDateOfWeek ,$Sum");
}
}
SELECT UserId, COALESCE(SUM(Commission),0), YEARWEEK(DateOfCommission) AS TheWeek
GROUP BY UserId, TheWeek
ORDER BY UserId, TheWeek;
This will not print the nice date range, but should get you started in a SQL-only direction where the sum is broken down by the week of the year. I think you could take it from this point to add the nicer formatting of the Year/Week column. YEARWEEK() should give you pretty fast results.
The easiest way I can think of doing this as follows
Step 1: Get the date of the first record
"SELECT dateofcommission FROM comissionstable WHERE id='userid' ORDER BY dateofcommission ASC LIMIT 1"
The above query will return the first date of commission only
Step 2: Create a loop which starts from the date you got in Step 1 and continue the loop till the date is greater than or equal to today's date. Increment this date using PHP date function.
date('Y-m-d', strtotime($dateofcommission. ' + 7 days'));
Step 3: In this loop you can get the commission with-in the starting date and ending date. Starting date will be the date before adding 7 days and ending date will be the one after you have added 7 days.
SELECT SUM(commission) FROM commissiontable WHERE dateofcommission>= startingdate AND dateofcomission < endingdate AND id='userid'
The above logic should work. If you end up having some issues with this logic feel free to post in comments. I would be happy to help
The following is another solution
function getStartAndEndDate($week, $year) {
$time = strtotime("1 January $year", time());
$day = date('w', $time);
$time += ((7*$week)+1-$day)*24*3600;
$return[0] = date('Y-n-j', $time);
$time += 6*24*3600;
$return[1] = date('Y-n-j', $time);
return $return;
}
$query = mysqli_query($con, "SELECT userid, COALESCE( SUM( commission ) , 0 ) AS thecommission , YEARWEEK( doc ) AS TheWeek FROM commission GROUP BY userid, TheWeek ORDER BY userid, TheWeek");
while ($array = mysqli_fetch_array($query)) {
$test = $array['TheWeek'];
$store_array = getStartAndEndDate(substr($test,4,2), substr($test,0,4));
echo $array['userid']."-".$array['thecommission']."-".$store_array[0]."/".$store_array[1]."<br>";
}
I have a table with next columns:
ID | Date | Hours |
1 20-05-2013 8:00
2 20-05-2013 2:00
I want to SUM the duplicate's hours if have the same date.
$sql2=mysql_query("SELECT count(distinct data_raport), SUM(ore) as TOTAL FROM sohy_works WHERE data_raport BETWEEN '".$_GET['data']."' AND '".$_GET['data-2']."' AND numes LIKE '%".$_GET['numes']."%' AND ore <= '8:00' GROUP BY data_raport ");
while ($row2=mysql_fetch_array($sql2)) {
$total = $row2[0];
echo "8 hours/day: " . $total;
}
I want to print total of days with 8 hours worked. conclusion it's must to be 0 worked days with 8 hours because the raport have the same date (same day)
Try this:
SELECT Date, SUM(Hours) as TOTAL
FROM your_table
GROUP BY Date;
Edit:
Hard to understand what you really want but this may help:
SELECT COUNT(*) as 8_Hours_day
FROM (
SELECT Date, SUM(Hours) as Total_Hours
FROM your_table
GROUP BY Date
HAVING Total_Hours = 8
) T;
SELECT SUM(Hours) from Table group by Date
Hi i have this mysql table
id amount substart years subend
1 200 2012-01-10 1 2013-01-09
2 250 2012-02-15 2 2014-02-14
3 100 2012-02-11 1 2013-02-10
4 260 2012-03-22 3 2015-03-21
What i want is that to give notification a month before the end date. The current query is:
select count(subend) as count,curdate()
from subdur where status='active'
and (date_sub(subend,interval 1 month))>=curdate()
and (date_sub(subend,interval 1 month))<date_add(curdate(),interval 1 month)
order by subend;
The query is not giving me proper answer.
Thanks in advance
Try this::
select
count(subend) as count,
curdate()
from subdur
where status='active' and
subend BETWEEN (date_sub(curdate(),interval 1 month)) and curdate()
order by subend
Another way would be using date_diff:
select count(subend) as count, curdate()
from subdur
where status='active'
and date_diff(subend, curdate()) = 30 // >= 30 days or more, = 30 days exact
order by subend
;
I have a table like below:
uid nid points date reason
36 116 2 2012-08-28 11:52:12 session
31 110 2 2012-08-23 15:47:47 session
36 115 2 2012-08-27 11:52:48 session
as u can see uid is not unique, it can be repeated. What i need is to select sum of points for every id between date(30 days before). For example: sum of uid36 = to 4.
What i have tried:
$start_time = mktime(0, 0, 0, $today["mon"], ($today["mday"] - 30), $today["year"]);//30 days before
$end_time = time();
$query = db_query("SELECT uid,sum(points), date FROM users_history WHERE date BETWEEN '$start_time' AND '$end_time'");
but how to select for every id
You need GROUP BY uid, and date is meanless in your query if you are using aggregate function SUM.
SELECT uid, SUM(points)
FROM users_history
WHERE date BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 day) AND NOW()
GROUP BY uid
And if there is no future date, then you only need
WHERE date >= DATE_SUB(CURDATE(), INTERVAL 30 day)
for that you need to group your uid.
SELECT uid,sum(points), date FROM users_history WHERE date BETWEEN '$start_time' AND '$end_time'" group by uid;
SELECT uid, SUM(points) FROM users_history WHERE date BETWEEN DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW() GROUP BY uid
I need a little help with row count. i manage to add today and total members count (rows). i want to count this week and this month. can anyone point me out how to do it? thanks.
$result = mysql_query("SELECT * FROM members");
$num_rows = mysql_num_rows($result);
echo "$num_rows Members\n";
$utoday = date("j. n. Y");
$today = mysql_query("SELECT * FROM mambers WHERE date='$utoday' ");
$num_today = mysql_num_rows($today);
echo "$num_today Members\n";
If you stored the date as a type date, you can use the mysql built-in time functions.
For example, you can group by MONTH(date).
If you want to count for this week starting from the most recent Monday:
SELECT COUNT(1) WeekCount
FROM members A,
(
SELECT
(MondayDate + INTERVAL 0 SECOND) PastMonday,
((MondayDate + INTERVAL 7 DAY) + INTERVAL 0 SECOND) NextMonday
FROM
(SELECT DATE(NOW() - INTERVAL WEEKDAY(NOW()) DAY) MondayDate) AA
) B
WHERE date >= PastMonday AND date < NextMonday
;
If you want to count for this month starting from the 1st query this:
SELECT COUNT(1) MonthCount
FROM members A,
(
SELECT FirstOfThisMonth,
((FirstOfThisMonth + INTERVAL 32 DAY) - INTERVAL (DAY(FirstOfThisMonth + INTERVAL 32 DAY)-1) DAY) FirstOfNextMonth
FROM
(
SELECT (DATE(NOW() - INTERVAL (DAY(NOW())-1) DAY) + INTERVAL 0 SECOND) FirstOfThisMonth
) AA
) B
WHERE date >= FirstOfThisMonth AND date < FirstOfNextMonth
;
Give it a Try !!!