Mysql Ranking based on Category and Branch - php

I'm having a hard time figuring out and trying how to fix this.
Can you help me give a logic or idea how can get the ranking of each category for each branch based on sales?
For example:
Rank 1 for branch_code_id = 9 is Accicular since it has 300,000 sales
Rank 2 for branch_code_id = 9 is WLO since it has only 200,000
sales.
Same as with other branches. I only need the rank of category for each branch_code_id.
I can't figure out how to loop this one. Rank will be placed in the "r" column as you can see in the excel output.
By the way, here's the sql statement i used to get the result you see in the screenshot.
SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount),
c.category
FROM
sales_add_h AS a
INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY c.category, a.branch_code_id, b.amount
ORDER BY SUM(b.amount) DESC
Thanks Guys!

Try this query
SELECT
#rn:=if(#prv=branch_code_id, #rn+1, 1) as rId,
#prv:= branch_code_id as branch_code_id,
val,
id,
date,
category
FROM
(SELECT
a.id,
a.date,
a.branch_code_id,
SUM(b.amount) as val,
c.category
FROM
sales_add_h AS a
INNER JOIN
sales_add_i AS b ON a.id = b.sales_h_id
INNER JOIN
control_panel_item_create AS c ON b.item_code_id = c.id
GROUP BY
c.category, a.branch_code_id, b.amount
ORDER BY
a.branch_code_id, SUM(b.amount) DESC)tmp
JOIN
(SELECT #rn:=0, #prv:=0)t
SQLFIDDLE to understand how ranking works.
I have done ranking for each branch_id as you have mentioned, if you want to rank for each category in a particular branch than you need to add another variable which stores the category and compare it within the if clause and also need to sort data within inner query accordingly order by c.category, a.branch_code_id, SUM(b.amount) DESC

Related

Left Join - Select ALL from left table but select only the latest from right table

I have 2 tables, borrowers and loans. I want to display on the main page the list of ALL borrowers with or without loans. If with loan, display the newest one.
I have the following sql query, basically it returns the above description except it displays the very first loan of the borrower instead of the latest one.
(Side note: I used GROUP BY to avoid duplicates. Without it the query returns duplicated borrower names if they have multiple loans. Just wanted to know if this is an efficient way of doing so.)
SELECT b.b_id,
b.isdeleted,
b.picture,
b.firstname,
b.middlename,
b.lastname,
b.address,
b.contactno,
b.birthday,
b.businessname,
b.occupation,
b.comaker,
b.comakerno,
b.remarks,
b.datecreated,
b.activeloan,
l.l_id,
l.amount,
l.payable,
l.balance,
l.mode,
l.term,
l.interestrate,
l.amortization,
l.releasedate,
l.duedate,
l.status,
l.c_id
FROM borrowers as b
LEFT JOIN loans as l ON b.b_id = l.b_id
WHERE b.isdeleted = 0
GROUP BY b.b_id
It seems the below query does exactly what i wanted.
I added the below subquery on the "ON" clause.
(SELECT MAX(l_id)
FROM jai_db.loans as l2
WHERE l2.b_id = b.b_id LIMIT 1)
SELECT b.b_id, b.isdeleted, b.picture, b.firstname, b.middlename, b.lastname, b.address, b.contactno,
b.birthday, b.businessname, b.occupation, b.comaker, b.comakerno, b.remarks, b.datecreated, b.activeloan,
l.l_id, l.amount, l.payable, l.balance, l.mode, l.term, l.interestrate, l.amortization,
l.releasedate, l.duedate, l.status, l.c_id
FROM jai_db.borrowers as b
LEFT JOIN jai_db.loans as l
ON l.l_id = (SELECT MAX(l_id)
FROM jai_db.loans as l2
WHERE l2.b_id = b.b_id LIMIT 1)
WHERE b.isdeleted = 0

Php, Mysql sort results based on number of records from another table

I'm joining two tables to display car brands. Here is the structure:
SELECT DISTINCT
b.title
FROM
brands as b
INNER JOIN items as i
ON i.brand_id = b.id
WHERE i.status = 1
ORDER BY COUNT(i.brand_id) DESC;
The above only produces one record. If I remove "ORDER BY COUNT(i.brand_id) DESC;" it displays all the records correctly.
I would like to sort result based on number of vehicles under each brand category. So for example if bmw category has the most car listed under, it should be the first one.
SELECT b.title
FROM brands as b
INNER JOIN items as i
ON i.brand_id = b.id
WHERE i.status = 1
GROUP BY b.title
ORDER BY COUNT(i.brand_id) DESC;
This should work for you.
I would use
SELECT b.title, count(i.brand_id)
FROM items i
LEFT JOIN brands as b
ON b.id = i.brand_id
WHERE i.status = 1
GROUP BY i.brand_id
ORDER BY COUNT(i.brand_id) DESC;
Your concern is the amount of cars in inventory. You want to break them down by how many of each brand you have. So, you're mainly concerned with the items tables and only need the brands table to get the information stored in the items table (brand name). Lastly, in order to get aggregate the number of brands of each, you must let MySQL know what you want in the GROUP BY.
I haven't used an EXPLAIN, but I would think the bottom query is more efficient.
You could join brands on an aggregate query:
SELECT b.title
FROM brands b
INNER JOIN (SELECT brand_id, COUNT(*) AS cnt
FROM items
WHERE status = 1
GROUP BY brand_id) i ON i.brand_id = b.id
ORDER BY cnt DESC;

MySQL Using SUM with multiple joins

I have a projects table and a tasks table I want to do a query that gets all projects and the sum of the time_spent columns grouped by project id. So essentially list all projects and get the total of all the time_spent columns in the tasks table belonging to that project.
With the query posted below I get the latest added time_spent column and not the sum of all the columns.. :S
Below is the query I have at the moment:
SELECT `projects`.`id`, `projects`.`description`, `projects`.`created`,
`users`.`title`, `users`.`firstname`, `users`.`lastname`, `users2`.`title`
as assignee_title, `users2`.`firstname` as assignee_firstname,
`users2`.`lastname` as assignee_lastname,
(select sum(tasks2.time_spent)
from tasks tasks2
where tasks2.id = tasks.id)
as project_duration
FROM (`projects`)
LEFT JOIN `users`
ON `users`.`id` = `projects`.`user_id`
LEFT JOIN `users` as users2
ON `users2`.`id` = `projects`.`assignee_id`
LEFT JOIN `tasks` ON `tasks`.`project_id` = `projects`.`id`
GROUP BY `projects`.`id`
ORDER BY `projects`.`created` DESC
Below is my projects table:
Below is my tasks table:
Thanks in advance!
Usually this query will help you.
SELECT p.*, (SELECT SUM(t.time_spent) FROM tasks as t WHERE t.project_id = p.id) as project_fulltime FROM projects as p
In your question, you don't say about users. Do you need users?
You are on right way, maybe your JOINs can't fetch all data.
This query should do it for you.
Note, whenever you do a group by you must include every column that you select from or order by. Some MySql installations don't prevent you from doing this, but in the end it results in an incorrect result set.
As well you should never do a query as part of your SELECT statement, known as a sub-query, as it will result in an equal amount of additional queries in relation to the number of rows returned. So if you got 1,000 rows back, it would result in 1,001 queries instead of 1 query.
SELECT
p.id,
p.description,
p.created,
u.title,
u.firstname,
u.lastname,
a.title assignee_title,
a.firstname assignee_firstname,
a.lastname assignee_lastname,
SUM(t.time_spent) project_duration
FROM
projects p
LEFT JOIN
users u ON
u.id = p.user_id
LEFT JOIN
users a ON
a.id = u.assignee_id
LEFT JOIN
tasks t ON
t.project_id = p.id
GROUP BY
p.id,
p.description,
p.created,
u.title,
u.firstname,
u.lastname,
a.title,
a.firstname,
a.lastname
ORDER BY
p.created DESC

MySQL RIGHT JOIN SUM() from Table B to Info on Table A

Basically I have a load of product information on Table A. This include the product_id which is the common id over both tables. On Table B I have a list of votes which include product_id, username, thevote(could be +1 or -1).
So basically I want to have a table of 'Table A' with a additional column containing the SUM of all the votes for that product_ID. I am sure there is an easy way to do this. Which i think is using 'right join'.
I still want it to list all the products in Table A regardless if they have a single +1 or -1 vote.
Many thanks in advance peoples!
You could use group by statement and left join like:
select productName, sum(vote) as productVoteSum
from `products` p
left join `products_votes` pv on p.id = pv.productId
where productName like '%chocolat%'
group by p.id
order by productName;
You can do a LEFT JOIN (that goes through all the information on tableA and puts the SUM in the ones that have the matching product_id on tableB), then you add the SUM(b.thevote) and group by the remaining columns
SELECT a.product_id,a.productName,SUM(b.thevote)
FROM tableA a
LEFT JOIN tableB b ON a.product_id = b.product_id
GROUP BY a.product_id, a.productName
SELECT a.*, SUM(b.votes) FROM TableA a LEFT JOIN TableB b ON a.prouct_id=b.product_id
GROUP BY a.product_id

mysql query dont gets all posts

I have a MYSQL query who have to list all post i want it to post. But it dont do it. It shows posts when i have more then one post in the table "meaOrder" with the same "ordCode". But when i have only on post in meaOrder, i don't show it. What can i do?
SELECT koden, wish, rnamn, bild, pris, cname, onsktext
FROM (
SELECT m.wishText as onsktext, m.meaOID as midn, m.ordcode as koden, w.wish as wish, r.meaName as rnamn, r.meaImg as bild,
r.meaPrice as pris, k.catName as cname from cats k, meals r, wishes w,
meaOrder m
join orders c on c.ordNR=4401
WHERE c.ordStatus=1 AND m.ordNR=c.ordNR AND m.meaID=r.meaID AND m.wishesID=w.id
AND r.catID=k.catID
) T
GROUP BY koden, rnamn, bild, pris, cname
ORDER BY midn DESC
TABLE orders
http://grab.by/m74E
TABLE meaOrder http://grab.by/m74Q
Try replacing the JOIN with RIGHT JOIN in this case. The difference is explained at JOIN Syntax page in MySQL docs . In short - JOIN returns row only if there are corresponding rows in both joined tables (inner join). LEFT JOIN / RIGHT JOIN return all rows from one of the tables and corresponding row if it exists from the other table (those are outer joins)
Do you need a subselect?
This seems to cover it:-
SELECT m.ordcode AS koden, w.wish AS wish, r.meaName AS rnamn, r.meaImg AS bild, r.meaPrice AS pris, k.catName AS cname, m.wishText AS onsktext
FROM cats k
INNER JOIN meals r ON r.catID = k.catID
INNER JOIN meaOrder m ON m.meaID = r.meaID
INNER JOIN wishes w ON m.wishesID = w.id
INNER JOIN orders c ON m.ordNR = c.ordNR
WHERE c.ordStatus = 1
AND c.ordNR = 4401
GROUP BY m.ordcode, r.meaName, r.meaImg, r.meaPrice, k.catName
ORDER BY midn DESC

Categories