MYSQL SUM by QTY's And Values - php

I would like to know if its possible to get 2 sums from one query using the table values and then add them togther.
Here is some simple table & data which might help.
CREATE TABLE `cartcontents` (
`id` int(11) NOT NULL auto_increment,
`code` varchar(40) NOT NULL,
`qty` int(10) NOT NULL,
`price` decimal(30,2) NOT NULL,
`cart_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zone` (`zone_code`,`cart_id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records
-- ----------------------------
INSERT INTO `cartcontents` VALUES ('5', '011242077783866125432', '1', '36.00', '2');
INSERT INTO `cartcontents` VALUES ('4', '011242077793513596890', '3', '33.00', '4');
INSERT INTO `cartcontents` VALUES ('6', '011242077649557011493', '1', '110.00', '4');
INSERT INTO `cartcontents` VALUES ('7', '011242077724922511037', '1', '177.00', '5');
So I would like to be able collect the total qty & total value for a given cart_id.
So this would mean if I had 3 in the qty filed the sum would need to be (qty * price) for each zone then add them in total for the cart_id.
So in the above example if I was looking for the values for cart_id 4 The values I would hope I could return would be qty = 4 & total value = 209
Hope this makes sense and thanks if you can help.

Something like this should work:
SELECT SUM(qty) AS qty, SUM(qty * price) AS total
FROM cartcontents
GROUP BY cart_id

Related

I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result only one value

these are the tables
and it results
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result is like this.it doesnt shows the second value in the 1st row that was entered in the it_coursestable
Query :
SELECT branch.branch_name
FROM `branch`
JOIN `it_courses` ON it_courses.course_branch = branch.branch_id
You can try this database structure and query :
Table:
tbl_it_courses (id - PK, cource_name, branch_id - FK)
tbl_branch (id - PK, branch_id, branch_name)
Table : tbl_it_courses
CREATE TABLE tbl_it_courses (
id INT NOT NULL AUTO_INCREMENT,
cource_name VARCHAR(70) NOT NULL,
branch_id VARCHAR(70) DEFAULT NULL,
PRIMARY KEY(id)
);
INSERT INTO `tbl_it_courses` (`Id`, `cource_name`, `branch_id`) VALUES (NULL, 'PHP', '1,4'),(NULL, '.NET', '3'), (NULL, 'CCNA', '3');
Table : tbl_branch
CREATE TABLE tbl_branch (
id INT NOT NULL AUTO_INCREMENT,
branch_id VARCHAR(70) DEFAULT NULL,
branch_name VARCHAR(70) NOT NULL,
PRIMARY KEY(id)
);
INSERT INTO `tbl_branch` (`Id`, `branch_id`, `branch_name`) VALUES (NULL, 'Ern', 'brn92b224'),(NULL, 'Klm', 'brnaf3650'), (NULL, 'Tvm', 'brn272493');
Query :
SELECT tbl_it_courses.cource_name, (SELECT GROUP_CONCAT(tbl_branch.branch_name) FROM tbl_branch WHERE FIND_IN_SET(tbl_branch.id,tbl_it_courses.branch_id) > 0) as branch_name
FROM tbl_it_courses
I Hope It will Help you.
Try this.
SELECT branch.branch_id,it_courses.course_name
FROM `branch`
left JOIN `it_courses` ON LOCATE(branch.branch_name,it_courses.course_branch) > 0

MYSQL Single query for multiple group by for same data

I have two query to get count and sum of rate for unique ip's.
Query one groups by date and query two groups by country
This is the table
DROP TABLE IF EXISTS `stats`;
CREATE TABLE IF NOT EXISTS `stats` (
`id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int(5) UNSIGNED NOT NULL,
`country` int(3) UNSIGNED NOT NULL,
`user_ip` int(50) UNSIGNED NOT NULL,
`timestamp` int(10) UNSIGNED NOT NULL,
`rate` int(7) UNSIGNED NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `stats`
--
INSERT INTO `stats` (`id`, `user_id`, `country`, `user_ip`, `timestamp`, `rate`) VALUES
(1, 1, 1, 1111111111, 1489999983, 15000),
(2, 1, 2, 1111111112, 1489999984, 10000),
(3, 1, 1, 1111111111, 1489999985, 10000),
(4, 1, 1, 1111111111, 1490086333, 10000),
(5, 1, 2, 1111111111, 1490086334, 10000),
(6, 1, 1, 1111111121, 1490086335, 10000);
These are the queries I am using to get data
To get sum of rates based on date I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY DATE(FROM_UNIXTIME(`timestamp`))
Result
date count rate
20-03-2017 2 25000
21-03-2017 2 20000
To get sum of rates based on country I use following query
SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`, `country`
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`, `country`
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY `country`
Result
country count rate
1 3 35000
2 1 10000
Since these two query are nearly same and fetches same rows from table is it possible to get both result from single query instead of two query.
Also please suggest if it can be be done in PHP effectively than MYSQL.
Thanks
Try this in php
$country="";
$groupByCondition="DATE(FROM_UNIXTIME(`timestamp`))";
if(/*BasedOnCountry*/){
$country=", `country`";
$groupByCondition = "`country`";
}
$query= "SELECT COUNT(`user_ip`) AS `count`, SUM(`rate`) AS `rate`, `timestamp`"+ $country +"
FROM (
SELECT DISTINCT `user_ip`, `rate`, `timestamp`"+ $country +"
FROM `stats`.`stats`
WHERE `user_id`=? `timestamp`>=? AND `timestamp`<=?
GROUP BY DATE(FROM_UNIXTIME(`timestamp`)),`user_ip`
) c
GROUP BY "+ $groupByCondition ;
//execute the query and get the results

Select random item from table with ratio

I'm trying to create an mysql table with some data in it which are special items. For example we have item1(chanse: 1), item2(chanse: 1), item(chance: 20%) and
item3 (chance: 20) etc.. etc...
- Chances are in %
So I created a table with the following information:
CREATE TABLE `special_items` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`item_id` int(11) NOT NULL,
`item_name` varchar(255) DEFAULT NULL,
`item_type` enum('SPECIAL','SILVER','BRONZE','GOLD') NOT NULL DEFAULT 'BRONZE',
`item_ratio` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`) USING BTREE,
UNIQUE KEY `item` (`item_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of special_items
-- ----------------------------
INSERT INTO `special_items` VALUES ('1', '200', 'special_name1', 'BRONZE', '80');
INSERT INTO `special_items` VALUES ('2', '204', 'special_name2', 'BRONZE', '4');
INSERT INTO `special_items` VALUES ('3', '875', 'special_name3', 'BRONZE', '80');
INSERT INTO `special_items` VALUES ('4', '900', 'special_name4', 'BRONZE', '60');
INSERT INTO `special_items` VALUES ('5', '901', 'special_name5', 'SILVER', '90');
INSERT INTO `special_items` VALUES ('6', '968', 'special_name6', 'BRONZE', '65');
INSERT INTO `special_items` VALUES ('7', '777', 'special_name7', 'BRONZE', '30');
What we want to do now is select from 800 rows 5 random items by there ratio. So it needs to have the following requirements:
Always random rows.
Select rows by there ratio (chance in the table is percentage for example)
I also found this query which almost fits the solution but its don't know how I would do this for the random ratio (percentage)
SELECT item_name
FROM special_items AS r1 JOIN
(SELECT CEIL(RAND() *
(SELECT MAX(id)
FROM special_items)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 5
If this can be done through PHP it would be awesome.
I'm open to any and all suggestions. I'll also be trying to figure this out on my own in the meantime, but I'm still stuck.
Let me guess that by "chanse" [sic], you mean that each row has a weight, and you want this weight to contribute to the chance of a row being selected.
One method is to generate a random number for each row, multiply by the weight, and then return 5 rows with the highest generated number. It is unclear what you mean by the chance, so this might do what you want:
select si.*
from (select si.*, rand() * item_ratio as weight
from special_items si
) si
order by weight desc
limit 5;
Note: The subquery is needed so the weight is only calculated once per line. I think this does the same thing:
select si.*, rand() * item_ratio as weight
from special_items si
order by weight desc
limit 5;
But MySQL can be peculiar.

PHP / MySQL query

After days of failing I hope that someone more skilled can help me with a solution.
I have two tables, one containing stocks and the other stock values. Please, you do not have to comment on field types etc as this is not a production development, I am only trying to get a grasp on join and mysql alias.
-- Stocks table:
DROP TABLE IF EXISTS `stocks`;
CREATE TABLE `stocks` (
`stock_id` int(11) NOT NULL AUTO_INCREMENT,
`stock_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`stock_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
-- Sample records:
INSERT INTO `stocks` VALUES ('1', 'HighTech');
INSERT INTO `stocks` VALUES ('2', 'NanoTech');
INSERT INTO `stocks` VALUES ('3', 'DotCom');
INSERT INTO `stocks` VALUES ('4', 'NewBiz');
-- Values table:
DROP TABLE IF EXISTS `vals`;
CREATE TABLE `values` (
`vals_id` int(11) NOT NULL AUTO_INCREMENT,
`stock_id` varchar(255) DEFAULT NULL,
`stock_value` int(11) DEFAULT NULL,
PRIMARY KEY (`vals_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
-- Sample records:
INSERT INTO `vals` VALUES ('1', '1', '50');
INSERT INTO `vals` VALUES ('2', '1', '700');
INSERT INTO `vals` VALUES ('3', '1', '540');
INSERT INTO `vals` VALUES ('4', '3', '15');
INSERT INTO `vals` VALUES ('5', '3', '44');
INSERT INTO `vals` VALUES ('6', '1', '60');
INSERT INTO `vals` VALUES ('7', '2', '10');
INSERT INTO `vals` VALUES ('8', '3', '53');
There could be 100s of stocks and 1000s of value records.
What I want to do is to print each stock together with a single (latest) stock value.
For stock number 3 I want to echo "DotCom" and the latest value "53", none of the others values.
Oh yeah , your table name values creating problem here , try to change it to someother name like vals or something.it would works/
here it is
SELECT * FROM stocks S JOIN vals V ON V.vals_id = ( SELECT MAX(vals_id) FROM vals Va WHERE Va.stock_id = S.stock_id )

calculate different values from mysql to php tables

How can I compile the results of various calculations from data gathered from different tables ? Present summaries in php table. I have people in a table that is linked to two other tables. It will be sorted by department how many people are women and men in number and percentage . How much they earn in total per department in average. How big women's pay is a percentage of men and how great the wage distribution is the max and min values ​​for men and women.
These code is used to get all the data.
I have added some value manually just for clarification in this picture.
I have struggled with this for some time now and see no solution. Grateful for the help !
Please see below, it's not exactly as you need, since I don't know a structure of tables, but you will get an idea:
CREATE TABLE `usergroup` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sex` enum('yes','no') NOT NULL DEFAULT 'yes',
`salary` decimal(10,2) DEFAULT NULL,
`userGroupId` int(11) DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
insert into `usergroup`(`id`,`name`) values (1,'Sales');
insert into `usergroup`(`id`,`name`) values (2,'Support');
insert into `usergroup`(`id`,`name`) values (3,'Managment');
insert into `usergroup`(`id`,`name`) values (4,'Others');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (1,'yes',20000.00,1,'Scott');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (2,'yes',30000.00,1,'Peter');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (3,'no',20000.00,1,'Mike');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (4,'yes',100000.00,2,'Senior');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (5,'no',50000.00,2,'Junior');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (6,'yes',75000.00,2,'Middle');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (7,'yes',250000.00,3,'King');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (8,'yes',300000.00,3,'Ace');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (9,'no',200000.00,3,'Queen');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (10,'yes',100000.00,3,'Jack');
insert into `user`(`id`,`sex`,`salary`,`userGroupId`,`name`) values (11,'no',400000.00,3,'LadyJoker');
Query to get report. The subquery is selecting a data with stats values, which are used in the outer query for calculation:
select analytic.userGroupId,
analytic.name,
analytic.countMen,
analytic.countWomen,
round((analytic.countMen / analytic.countMisc)*100, 2) as percentMen,
round((analytic.countWomen / analytic.countMisc)*100, 2) as percentWomen,
round((analytic.maxSalaryMen + analytic.minSalaryMen)/2, 2) as basicSalaryMen,
round((analytic.maxSalaryWomen + analytic.minSalaryWomen)/2, 2) as basicSalaryWomen,
round(
(analytic.maxSalaryMen + analytic.minSalaryMen +
analytic.maxSalaryWomen + analytic.minSalaryWomen
)/4,
2)
as basicSalaryMisc,
if(analytic.maxSalaryMen + analytic.minSalaryMen = 0, 100,
round((analytic.maxSalaryWomen + analytic.minSalaryWomen)/(analytic.maxSalaryMen + analytic.minSalaryMen), 2)
) as salaryBasicWomenPercentOfMen,
analytic.maxSalaryMen,
analytic.minSalaryMen,
analytic.maxSalaryWomen,
analytic.minSalaryWomen
from (
select ug.id as userGroupId,
ug.name,
sum(if(u.sex='yes', 1, 0)) countMen,
sum(if(u.sex='no', 1, 0)) countWomen,
count(*) countMisc,
max(if(u.sex='yes', u.salary, null)) maxSalaryMen,
min(if(u.sex='yes', u.salary, null)) minSalaryMen,
max(if(u.sex='no', u.salary, null)) maxSalaryWomen,
min(if(u.sex='no', u.salary, null)) minSalaryWomen
from userGroup ug left join user u
on u.userGroupId = ug.id
group by ug.id, ug.name
order by ug.name
) analytic

Categories