MySQL SUM only 1 field and - php

I have the following table structure
--ID-- --Date-- --Value--
1 2013-1-2 23
2 2013-1-2 11
3 2013-1-3 8
4 2013-1-3 7
As you can see the dates can overlap and I want to output every different date with a summation of the values attributed. So for this it would be.
--Date-- --Total--
2013-1-2 34
2013-1-3 15
Is this even possible with a query or will I have to do some seperate summation?

SELECT Date, sum(Value) as Total
FROM Table
GROUP BY Date

Related

Mysql GROUP BY and Union based on date condition

Here is my query - it mostly works, but I can see it failing on one condition - explained after the query:
$firstDay = '2020-03-01' ;
$lastDay = '2020-03-31' ;
SELECT * FROM clubEventsCal
WHERE ceFreq!=1
AND (ceDate>='$firstDay' AND ceDate<='$lastDay')
UNION SELECT * FROM clubEventsCal
WHERE ceFreq=1
AND (ceDate>='$firstDay' AND ceDate<='$lastDay')
GROUP BY ceStopDate ORDER BY ceID,ceDate ;
The first select gives me all Event records between the two dates. The second select gives me grouped/summarized Event records between the two dates. The problem though is if the value ceDate spans days across two months: IE: 2020-03-30 thru 2020-04-02. When I pull the records for March, all is good - the above query pulls the 2020-03-30 record (grouped) as the first instance of the 4 days/records - allowing us to charge for a single 4 day event. But when I pull the records for April its also going to pull 2020-04-01 as a new grouped Event record for the last two days of the 4 day event and try to charge the customer for a new Event - when in fact those two days were already a part of March's bill.
How can I write the query so that when ceDate starts in Month X but ends in Month Y that when records are pulled for Month Y its not trying to pull records that actually belong to an Event that started in Month X?
Examples of an Event record would look like this:
rid | ceID | ceActive | ceFreq | ceDate | ceStopDate
------------------------------------------------
1 1108 1 3 2020-03-09 | 2020-03-09
2 1111 1 2 2020-03-15 | 2020-03-15
3 1112 1 2 2020-03-17 | 2020-03-17
4 1117 1 1 2020-03-30 | 2020-04-02
5 1117 1 1 2020-03-31 | 2020-04-02
6 1106 1 3 2020-03-21 | 2020-03-21
7 1110 1 2 2020-03-05 | 2020-03-05
8 1113 1 2 2020-03-24 | 2020-03-24
9 1117 1 1 2020-04-01 | 2020-04-02
10 1117 1 1 2020-04-02 | 2020-04-02
The above query pulls all records where ceFreq != 1, and it pulls a single record for the ceFreq = 1 records (rids: 4 & 5). For March, we don't necessarily care that ceID 1117 spills into April. But when we pull records for April - we need to exclude rid 9 & 10, because the Event (ceID=1117), was already accounted for in March.
SELECT * FROM clubEventsCal
...
GROUP BY ceStopDate
This is gibberish.
MySQL (depending on configuration) allows it without choking - but it's semantically wrong and stands out as an anti-pattern.
There are some edge cases where the values returned might contain significant data, but they very unusual. Trying to explain a problem with code which does not work is perhaps not a good strategy.
Looking at your code, its possible that you don't need a union - but there's not enough information in your example records to say if this would actually give the result you expect (it will be significantly faster depending on your indexes):
SELECT IF(cefreq=1, rid, null) AS consolidator
, ceid
, cefreq
, MIN(cedate), MAX(cedate)
, ceStopDate
FROM clubEventsCal
WHERE cID=1001
AND ceActive!=2
AND (ceDate>='$firstDay' AND ceDate<='$lastDay')
GROUP BY IF(cefreq=1, rid, null)
, ceid
, cefreq
, ceStopDate
;
I would have added the ORDER BY - but I don't know where clId came from. Also This will give different resuts to what I think you were trying to achieve for any record where cefreq is null (if you really do want to exclude them, add a predicate in the WHERE clause).

PHP + MySQL - ORDER BY LIKES

So I am using mysql to store likes on Minecraft Server Pages as a way for them to advertise. However, I am storing these likes in a separate table:
id user_id server_id
1 1 1
2 1 24
4 2 22
5 2 22
6 2 1
7 2 4
8 2 5
9 2 6
10 2 17
11 2 18
12 2 21
13 2 24
Insert code:
INSERT INTO likes (user_id, server_id) VALUES ('".$user_id."', '".$server_id."');
But I am currently sorting them by date added (recent first) but I would like to know how to sort them by likes.
You should put a counter column on your servers table (lets say: likes_counter) and then, every time you add a like to the likes table, you increment this counter. Put a index on that column tooo!
INSERT INTO likes (user_id, server_id) VALUES ('".$user_id."', '".$server_id."');
UPDATE servers_table SET likes_counter = likes_counter+1 WHERE server_id = '".$server_id."';
Now, when you select the servers, you only need to do a ordered by likes select:
SELECT * FROM servers_table ORDER BY likes_counter DESC;
Here i'm assuming your table of servers is named servers_table, replace it with the name you gave to the table.

Get each day of the week as columns MySQL and PHP

I am writing a web application in PHP with MySQL.
I have a table called counts and this is how data is stored in that table:
Table: counts
id counts location_id media_id created_at
--------------------------------------------------
1 50 1 1 2017-03-15
2 30 2 1 2017-03-15
3 80 1 2 2017-03-15
4 20 1 1 2017-03-16
5 100 2 2 2017-03-16
For every unique location_id, media_id and created_at, I store count.
I have another table locations which is like this:
Table: locations
id name
----------------
1 Location 1
2 Location 2
3 Location 3
4 Location 4
5 Location 5
This is the SQL Query I have at the moment:
select sum(counts.count) as views, locations.name as locations, DAYNAME(counts.created_at) AS weekday from `counts` inner join `locations` on `locations`.`id` = `counts`.`location_id` where `counts`.`created_at` between '2016-12-04' and '2016-12-10' group by `weekday`, `counts`.`location_id`;
This is how the data is displayed:
locations weekday views
-----------------------------------
Location 1 Mon 50
Location 1 Tue 30
Location 2 Mon 20
Location 2 Tue 70
I'm creating reports and I would like to run a query such that all the days of the week appear as a column with their corresponding values as the view count for that day of the week. I want something like this:
locations mon tue wed thu fri sat sun
-------------------------------------------------
Location 1 40 60 51 20 40 20 30
Location 2 80 60 100 24 30 10 5
Is the above possible in MySQL or I would have to use PHP to achieve that? If so, how do I go about it?
Any help will be appreciated, thanks.
NB: The sample data is not accurate.
It's possible to achieve this result with MySQL, using conditional aggregation.
The trick is to use a conditional test in an expression in the SELECT list to determine whether to return a value of count.
Something like this:
SELECT l.name AS `locations`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Mon',c.count,0)) AS `mon`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Tue',c.count,0)) AS `tue`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Wed',c.count,0)) AS `wed`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Thu',c.count,0)) AS `thu`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Fri',c.count,0)) AS `fri`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sat',c.count,0)) AS `sat`
, SUM(IF(DATE_FORMAT(c.created_at,'%a')='Sun',c.count,0)) AS `sun`
FROM `locations` l
LEFT
JOIN `counts` c
ON c.location_id = l.id
AND c.created_at >= '2016-12-04'
AND c.created_at < '2016-12-04' + INTERVAL 7 DAY
GROUP BY l.name
ORDER BY l.name
NOTE:
With the sample data, there are two rows for location_id=1 and created_at='2016-03-15', so this query would return a total of 130 for tue (=50+80), not 50 (as shown in the sample output of the existing query).

Easiest possible way to retrieve MYSQL data in a table field with decreasing order of occurrence along with the occurrence count?

I have a table with the following data:
id product_id
1 31
2 12
3 25
4 31
5 16
6 25
7 31
8 16
I want to retrieve the data with decreasing order of occurrence along with the occurrence count as follows:
31 - 3 times
25 - 2 times
16 - 2 times
12 - 1 time
try this,
SELECT
product_id,
count(product_id) as times
FROM table_name
GROUP BY product_id
ORDER BY times desc;
Make sure to replace table_name with your actual table.
You can use GROUP BY method.
SELECT product_id, count(product_id) as count FROM your_table_name GROUP BY product_id ORDER BY count DESC;
Result:
product_id - count
31 - 3
25 - 2
16 - 2
12 - 1

Prevent duplicate row values

I've done some digging and I can't find an effective way to prevent duplicate entries based on my needs. I need columns 2 (proj_id) and column 4 (dept_id) never to be the same, as each dept would only work on a project once. So, rows 1 and 4, 6 and 7, and 14 and 15 shouldn't be allowed. I'll keep digging as well.
summary_id proj_id hours_id dept_id date_entered
1 8 3 6 9/9/2012
2 2 2 6 9/9/2012
3 1 6 19 9/9/2012
4 8 3 6 9/9/2012
5 2 5 17 9/9/2012
6 7 2 5 9/9/2012
7 7 2 5 9/9/2012
8 2 5 17 9/9/2012
9 7 4 17 10/10/2012
10 3 6 1 10/10/2012
11 5 1 15 10/10/2012
12 4 4 3 10/10/2012
13 3 5 1 10/10/2012
14 8 2 13 10/10/2012
15 8 2 13 10/10/2012
Before applying unique combine key to your table, you have to remove duplicate records first then apply the following sql command:
ALTER TABLE your_table_name ADD UNIQUE (proj_id, dept_id);
Define an unique key on both columns
ALTER TABLE `your_table` ADD UNIQUE (`proj_id`, `dept_id`);
Looks like you are new to php and mysql. So here's the easiest way to do it.
Log on to PHPMyAdmin
Select your DB and your table.
View the Structure of it (clicking the button on top of the screen).
Check the two fields (proj_id and dept_id) using the check box on the left.
At the bottom of the table you should find the the words "With selected" and in front of it some actions. Select the option to make "Primary".
Of course, if you have duplicate entries first delete them.

Categories