I have the following 3 MySQL tables:
products
| id | name | comment_count |
|----|-----------|---------------|
| 1 | Product A | 10 |
| 2 | Product B | 20 |
| 3 | Product C | 30 |
products_views
| product_id | pv_count | pv_date |
| -----------|-------|------------|
| 1 | 10 | 2015-01-01 |
| 1 | 10 | 2015-01-02 |
| 1 | 10 | 2015-01-03 |
| 2 | 20 | 2015-01-01 |
| 2 | 20 | 2015-01-02 |
| 2 | 20 | 2015-01-03 |
| 3 | 30 | 2015-01-01 |
| 3 | 30 | 2015-01-02 |
| 3 | 30 | 2015-01-03 |
products_likes
| product_id | pl_count | pl_date |
| -----------|-------|------------|
| 1 | 10 | 2015-01-01 |
| 1 | 10 | 2015-01-02 |
| 1 | 10 | 2015-01-03 |
| 2 | 20 | 2015-01-01 |
| 2 | 20 | 2015-01-02 |
| 2 | 20 | 2015-01-03 |
| 3 | 30 | 2015-01-01 |
| 3 | 30 | 2015-01-02 |
| 3 | 30 | 2015-01-03 |
I want to add together products.comment_count + product_views.count + product_likes.count grouping by products.id, where product_views.pv_date and product_likes.pl_date between 2015-01-01 and 2015-01-03. Ordering by a total.
What I want:
| product_id | total |
| -----------|-------|
| 3 | 210 |
| 2 | 140 |
| 1 | 70 |
Try this query
SELECT
p.product_id,
(p.comment_count + SUM(pv.count) + SUM(pl.count)) AS total
FROM products p
JOIN products_views pv ON( p.product_id = pv.product_id)
JOIN products_likes pl ON( p.product_id = pl.product_id)
WHERE pl.date BETWEEN '2015-01-01' AND '2015-01-03'
AND pv.date BETWEEN '2015-01-01' AND '2015-01-03'
GROUP BY p.product_id
ORDER BY total DESC
SELECT
(products.comment_count+products_views.pv_count+products_likes.pl_count) AS product_count
FROM products
INNER JOIN products_views.product_id=products.id
INNER JOIN products_likes.product_id=products.id
WHERE (product_views.pv_date BETWEEN dateVal AND dateVal)
AND (products_likes.pl_date BETWEEN dateVal AND dateVal)
GROUP BY products.id
ORDER BY product_count
Perform the counts "per table" before joining otherwise you run the risk of getting larger results than there should be as joins can multiply the number of rows. Also, as there is a chance some products don't exist in likes or views so a left outer join to both of the "derived tables" is recommended.
SELECT
p.product_id
, (IFNULL(p.comment_count,0) + IFNULL(pv.view_count, 0) + IFNULL(pl.like_count, 0)) AS total
FROM products p
LEFT OUTER JOIN (
SELECT
product_id
, SUM(`count`) AS view_count
FROM products_views
WHERE `date` BETWEEN '2015-01-01' AND '2015-01-03'
GROUP BY
product_id
) pv ON p.product_id = pv.product_id
LEFT OUTER JOIN (
SELECT
product_id
, SUM(`count`) AS like_count
FROM products_likes
WHERE `date` BETWEEN '2015-01-01' AND '2015-01-03'
GROUP BY
product_id
) pl ON p.product_id = pl.product_id
GROUP BY
p.product_id
ORDER BY
total DESC
btw: date and count are reserved words in most SQL dialects; it not a good idea to name columns as date or count; use something more e.g. date_entered, date_created, view_count, like_count etc.
select p.product_id, sum(p.comment_count) + sum(v.count) + sum(l.count) as total from products p join products_views v on p.product_id = v.product_id join products_likes l on p.product_id = l.product_id group by p.product_id
where l.date between '2015-01-01' and '2015-01-03'
order by total desc
try this
Related
I want to get the categories pricing, Say if there is data in customer_category_pricing table then fetch that pricing for that specific customer. Otherwise fetch default prices from categories table.
i have tried achieving this desired result using mysql case it is working fine, but the problem is, it is returning two rows
hourly_amount_final column returns updated price then per_day_amount_final returns default price
Then in next row, hourly_amount_final column return default price and then per_day_amount_final returns updated price.
table: pr_categories
---------------------------------------------------------------------------------
| id | title | hourly_amount | per_day_amount | created_at| updated_at
---------------------------------------------------------------------------------
| 1 | Power Generation | 100.00 | 200.00 |
| 2 | Local Government | 300.00 | 400.00 |
----------------------------------------------------------
table: pr_customer_categories_pricing
------------------------------------------------------------------------------------
| id | customer_id | category_id | billing_type_id | amount | created_at | updated_at
------------------------------------------------------------------------------------
| 1 | 1 | 1 | 1 | 109 |
| 2 | 1 | 1 | 2 | 600 |
----------------------------------------------------------
table: pr_billing_types
----------------
| id | title |
--------------
| 1 | Hourly |
| 2 | Per Day |
----------------
This is the query i am working with at the moment:
SELECT c.id,c.title,
CASE
WHEN (c.hourly_amount <> (SELECT ccp.amount WHERE ccp.billing_type_id = 1))
THEN (SELECT ccp.amount WHERE ccp.billing_type_id = 1)
ELSE c.hourly_amount
END
AS hourly_amount_final,
CASE
WHEN (c.per_day_amount <> (SELECT ccp.amount WHERE ccp.billing_type_id = 2))
THEN (SELECT ccp.amount WHERE ccp.billing_type_id = 2)
ELSE c.per_day_amount
END
AS per_day_amount_final
FROM pr_customer_category_pricing AS ccp
RIGHT JOIN pr_categories AS c
ON c.id = ccp.category_id AND ccp.customer_id = 1
Expected result when there is no data in pr_customer_category_pricing
----------------------------------------------------------------------
| id | title | hourly_amount_final | per_day_amount_final |
----------------------------------------------------------------------
| 1 | Power Generation | 100.00 | 200.00 |
| 2 | Local Government | 300.00 | 600.00 |
----------------------------------------------------------------------
Expected result when there is data in pr_customer_category_pricing
----------------------------------------------------------------------
| id | title | hourly_amount_final | per_day_amount_final |
----------------------------------------------------------------------
| 1 | Power Generation | 109.00 | 600.00 |
| 2 | Local Government | 300.00 | 400.00 |
----------------------------------------------------------------------
Actual result what i'm getting:
----------------------------------------------------------------------
| id | title | hourly_amount_final | per_day_amount_final |
----------------------------------------------------------------------
| 1 | Power Generation | 109.00 | 200.00 |
| 1 | Power Generation | 100.00 | 600.00 |
| 2 | Local Government | 300.00 | 400.00 |
----------------------------------------------------------------------
What am i doing wrong? Any suggestions! Help a brother out. :S
Since there can only be one entry in the pr_customer_category_pricing table per billing type, you can simplify things by creating a derived pivot table from the pr_customer_category_pricing with values for each of the billing_type_id in separate columns. You can then simply COALESCE the value from the derived table with the value from the pr_categories for each billing_type_id:
SELECT c.id,c.title,
COALESCE(ccp.hourly_amount, c.hourly_amount) AS hourly_amount_final,
COALESCE(ccp.per_day_amount, c.per_day_amount) AS per_day_amount_final
FROM (SELECT
customer_id,
category_id,
MAX(CASE WHEN billing_type_id = 1 THEN amount END) AS hourly_amount,
MAX(CASE WHEN billing_type_id = 2 THEN amount END) AS per_day_amount
FROM pr_customer_category_pricing
GROUP BY customer_id, category_id) AS ccp
RIGHT JOIN pr_categories AS c
ON c.id = ccp.category_id AND ccp.customer_id = 1
Output:
id title hourly_amount_final per_day_amount_final
1 Power Generation 109 600
2 Local Government 300 400
Demo on dbfiddle
You can use max() aggregation with group by
SELECT c.id,c.title,
max(CASE
WHEN (c.hourly_amount <> (SELECT ccp.amount WHERE ccp.billing_type_id = 1))
THEN (SELECT ccp.amount WHERE ccp.billing_type_id = 1)
ELSE c.hourly_amount
END)
AS hourly_amount_final,
max(CASE
WHEN (c.per_day_amount <> (SELECT ccp.amount WHERE ccp.billing_type_id = 2))
THEN (SELECT ccp.amount WHERE ccp.billing_type_id = 2)
ELSE c.per_day_amount
END)
AS per_day_amount_final
FROM pr_customer_category_pricing AS ccp
RIGHT JOIN pr_categories AS c
ON c.id = ccp.category_id AND ccp.customer_id = 1
group by c.id,c.title
I have the following 2 MySQL tables:
players:
| id | name |
|----|---------|
| 1 | Player1 |
| 2 | Player2 |
| 3 | Player3 |
scores:
| key | id | round | score |
|-----|----|-------|-------|
| 1 | 1 | Rd1 | 20 |
| 2 | 1 | Rd2 | 22 |
| 3 | 1 | Rd3 | 19 |
| 4 | 2 | Rd1 | 18 |
| 5 | 2 | Rd2 | 23 |
| 6 | 2 | Rd3 | 19 |
where scores.id=players.id
I will have upwards of 90 players in my 'players' table, what's the best way to query this and insert it into an HTML table to make it easier to view? I'm hoping to have an output similar to this:
| Player | Round 1 | Round 2 | Round 3 |
|---------|---------|---------|---------|
| Player1 | 20 | 22 | 19 |
| Player2 | 18 | 23 | 19 |
This is my first attempt at normalizing data in tables. Am I going to have to do number of cases? I'm not sure what the best way to pivot the data is with an INNER JOIN.
This is my solution, hope it helps :
SELECT
name as Player,
SUM(CASE WHEN (s.round='Rd1') THEN s.score ELSE 0 END) AS Round1,
SUM(CASE WHEN (s.round='Rd2') THEN s.score ELSE 0 END) AS Round2,
SUM(CASE WHEN (s.round='Rd3') THEN s.score ELSE 0 END) AS Round3
FROM
players p
JOIN scores s
on s.id=p.id
GROUP BY
name
This will output :
| Player | Round1 | Round2 | Round3 |
|---------|---------|---------|---------|
| Player1 | 20 | 22 | 19 |
| Player2 | 18 | 23 | 19 |
This Fiddle for you to test!
I have a sligthly alternative solution which uses subqueries with the following benefit that players with no no score gets listed too!!
SELECT
p.name,
ifnull((select score from scores where id = p.id and round='Rd1' limit 1), 0) as Round1,
ifnull((select score from scores where id = p.id and round='Rd2' limit 1), 0) as Round2,
ifnull((select score from scores where id = p.id and round='Rd3' limit 1), 0) as Round3
FROM players p
GROUP BY p.name, p.id
Category Table
mysql> SELECT * FROM cats;
+------+------+-----------+
| c_id | p_id | c_name |
+------+------+-----------+
| 1 | 1 | cats 1 |
| 2 | 1 | cats 2 |
| 3 | 1 | cats 3 |
+------+------+-----------+
Meta Table
mysql> SELECT * FROM meta;
+------+------+------+---------+-------------+-------+
| m_id | p_id | c_id | name | description | costs |
+------+------+------+---------+-------------+-------+
| 1 | 1 | 1 | Abhijit | description | 100 |
| 2 | 1 | 1 | Abhijit | description | 200 |
| 3 | 1 | 2 | Abhiji2 | description | 500 |
+------+------+------+---------+-------------+-------+
Transaction Table
mysql> SELECT * FROM transactions;
+------+------+------+---------------------+--------+
| t_id | p_id | m_id | date | amount |
+------+------+------+---------------------+--------+
| 1 | 1 | 1 | 2016-02-16 11:17:06 | 50 |
| 2 | 1 | 1 | 2016-02-16 11:17:06 | 50 |
| 3 | 1 | 2 | 2016-02-16 11:17:06 | 50 |
| 4 | 1 | 2 | 2016-02-16 11:17:06 | 150 |
+------+------+------+---------------------+--------+
I want to sum() for each category costs (from meta table) and amount( from transaction table).
I use:
mysql> SELECT c.*, SUM(t.amount), SUM(m.costs)
FROM cats c
LEFT JOIN meta m ON m.c_id=c.c_id
LEFT JOIN transactions t ON t.m_id=m.m_id
GROUP BY c.c_id;
+------+------+-----------+--------+---------------+--------------+
| c_id | p_id | c_name | add_by | SUM(t.amount) | SUM(m.costs) |
+------+------+-----------+--------+---------------+--------------+
| 1 | 1 | Abhijit | 1 | 100 | 400 |
| 2 | 1 | Abhiji2 | 1 | 200 | 500 |
+------+------+-----------+--------+---------------+--------------+
It's wrong. The Costs of cats id 1 is 300 but here I got 400
I Want Get Return From Query Like This:
+------+------+-----------+--------+---------------+--------------+
| c_id | p_id | c_name | add_by | SUM(t.amount) | SUM(m.costs) |
+------+------+-----------+--------+---------------+--------------+
| 1 | 1 | Abhijit | 1 | 100 | 300 |
| 2 | 1 | Abhiji2 | 1 | 200 | 500 |
+------+------+-----------+--------+---------------+--------------+
I think you had a typo (or error) in one of your JOIN conditions. I think you intended your original query to be this:
SELECT c.*, SUM(t.amount), SUM(m.costs)
FROM cats c
LEFT JOIN meta m ON m.c_id = c.c_id
LEFT JOIN transactions t ON t.m_id = m.c_id
GROUP BY c.c_id;
Note carefully ON t.m_id = m.c_id, which agrees with your expected output. In any case, I reworked your query as follows:
SELECT c.c_id, c.p_id, c.c_name, t2.transactionCosts, t1.metaCosts
FROM cats c
LEFT JOIN
(
SELECT c_id, SUM(costs) AS metaCosts
FROM meta
GROUP BY c_id
) t1
ON c.c_id = t1.c_id
LEFT JOIN
(
SELECT m_id, SUM(amount) AS transactionCosts
FROM transactions
GROUP BY m_id
) t2
ON c.c_id = t2.m_id
WHERE t2.transactionCosts IS NOT NULL OR t1.metaCosts IS NOT NULL;
The first subquery computes the meta total for each c_id, and the second subquery computes the transaction total for each m_id. These results are then both joined together with the cats table to get your final result.
Follow the link below for a running demo:
SQLFiddle
the problem is you select c.* but only group by c_id, in this case you have 2 options. window function or subquery.
via over(partition by):
SELECT c.*,
SUM(t.amount)over(partition by c.c_id) as amount,
SUM(m.costs)over(partition by c.c_id) as cost
FROM con_cats c
LEFT JOIN meta m ON m.c_id=c.c_id
LEFT JOIN transactions t ON t.m_id=m.m_id;
via subquery:
select a.*,b.amount,b.costs from con_cats a
inner join
(SELECT c.c_id, SUM(t.amount) as amount, SUM(m.costs) as costs
FROM con_cats c
LEFT JOIN meta m ON m.c_id=c.c_id
LEFT JOIN transactions t ON t.m_id=m.m_id
GROUP BY c.c_id) b
on a.c_id = b.c_id;
I need to select calls, answers, deals, rate, talking_time by the grouped working time.
Here is my select:
SELECT
users.username as username,
DATE_FORMAT(users_worktime.start,'%Y-%m-%d') as start,
SUM(users_worktime.length) as working_time
FROM
users_worktime
LEFT JOIN users ON users.id = users_worktime.user_id
WHERE 1
AND users_worktime.user_id = '8'
AND users_worktime.start >= '2015-12-30 00:00:00'
AND users_worktime.start <= '2015-12-31 23:59:59'
GROUP BY
DAY(users_worktime.start)
It's all good, i got 2 rows by date 2015-12-30 and 2015-12-31:
| username | start | working_time |
-----------------------------------------
| Haroldas | 2015-12-30 | 85.00 |
| Haroldas | 2015-12-31 | 170.00 |
And my question: how to select COUNT calls from table calls, answers - SUM all calls where status = 'ended', select COUNT deals from table orders, rate - Deals / SUM calls, and talking_time - calls.call_length. And all of these select by the grouped working time.
I need result like this:
| username | start | calls | answers | deals | rate | talking_time| working_time |
----------------------------------------------------------------------------------------
| Haroldas | 2015-12-30 | 1 | 1 | 1 | 100% | 35 | 85.00 |
| Haroldas | 2015-12-31 | 3 | 2 | 1 | 50% | 160 | 170.00 |
And here are my data tables:
users_worktime:
| id | user_id | length | start |
-----------------------------------------------
| 1 | 8 | 30 | 2015-12-30 07:53:38 |
| 2 | 8 | 55 | 2015-12-30 12:53:38 |
| 3 | 8 | 170 | 2015-12-31 22:53:38 |
users:
| id | username |
-----------------
| 8 | Haroldas |
calls:
| id | user_id | order_id | status | call_length | created_at |
-------------------------------------------------------------------------
| 1 | 8 | 3 | ended | 35 | 2015-12-30 07:53:38 |
| 2 | 8 | 4 | ended | 100 | 2015-12-31 12:53:38 |
| 3 | 8 | NULL | started | 15 | 2015-12-31 14:53:38 |
| 4 | 8 | NULL | ended | 45 | 2015-12-31 20:53:38 |
orders:
| id | user_id | call_id | start |
-----------------------------------------------
| 3 | 8 |1 | 2015-12-30 07:53:38 |
| 4 | 8 |2 | 2015-12-31 12:53:38 |
How many calls / answers / deals / etc / were when user Haroldas working on these days.
Thank you
You could use subqueries to achive your goal. I've also changed your base query because you'll not see records if user didn't work at specified period of time.
SELECT T2.*,
(deals / answers_cnt) * 100 AS rate
FROM
(SELECT T.username,
T.day_start
SUM(T.working_time) AS working_time,
(SELECT COUNT(*) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id) AS calls_cnt,
(SELECT COUNT(*) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id
AND C.status = 'ended') AS answers_cnt,
(SELECT SUM(call_length) FROM calls AS C
WHERE DATE(created_at) = T.day_start
AND C.user_id = T.user_id) AS talking_time,
(SELECT COUNT(*) FROM orders AS O
WHERE DATE(O.start) = T.day_start
AND O.user_id = T.user_id) AS deals_cnt
FROM
(SELECT U.username,
U.id AS user_id,
DATE(UW.start) as day_start,
UW.length AS working_time
FROM users AS U
LEFT JOIN users_worktime AS UW ON UW.user_id = U.id
WHERE U.id = 8
AND UW.start >= '2015-12-30 00:00:00'
AND UW.start <= '2015-12-31 23:59:59') AS T
GROUP BY T.username, T.user_id, T.day_start
) AS T2
You can LEFT JOIN by user_id plus DAY of time. E.g.
FROM
users_worktime
LEFT JOIN users ON users.id = users_worktime.user_id
LEFT JOIN users ON users.id = calls.user_id
AND DAY(users_worktime.start)=DAY(calls.created_at)
Then apply all necessary aggregate functions to the calls data
I have following tables, i want to fetch the purchase_order and his order_quantity and sum of received quantity for each purchase_order. i know how to sum the quantity from single table but from multiple tables, it is confusing me a lot...
mysql> select * from purchase_order;
+-------------------+-------------------------+-------+---------------------+
| purchase_order_id | purchase_order | cost | created_on |
+-------------------+-------------------------+-------+---------------------+
| 1 | Dell Computer 000001256 | 10000 | 2015-02-19 22:14:52 |
| 2 | HP Computer 000001256 | 50000 | 2015-02-19 22:14:52 |
+-------------------+-------------------------+-------+---------------------+
2 rows in set (0.00 sec)
mysql> select * from purchase_order_detail;
+--------------------------+-------------------+---------+------------------+
| purchase_order_detail_id | purchase_order_id | item_id | ordered_quantity |
+--------------------------+-------------------+---------+------------------+
| 1 | 1 | 279 | 100 |
| 2 | 1 | 286 | 100 |
| 3 | 2 | 279 | 200 |
| 4 | 2 | 286 | 300 |
+--------------------------+-------------------+---------+------------------+
4 rows in set (0.00 sec)
mysql> select * from delivery_order;
+-------------------+--------------------------+-------------------+---------------------+
| delivery_order_id | purchase_order_detail_id | recieved_quantity | recieved_on |
+-------------------+--------------------------+-------------------+---------------------+
| 1 | 1 | 50 | 2015-02-19 22:22:51 |
| 2 | 2 | 50 | 2015-02-19 22:24:59 |
| 3 | 1 | 50 | 2015-02-19 22:34:14 |
| 4 | 3 | 70 | 2015-02-20 11:11:31 |
| 5 | 4 | 150 | 2015-02-20 11:11:31 |
| 6 | 3 | 90 | 2015-02-20 11:12:20 |
| 7 | 4 | 100 | 2015-02-20 11:12:20 |
| 8 | 3 | 40 | 2015-02-20 11:12:55 |
| 9 | 4 | 50 | 2015-02-20 11:12:55 |
+-------------------+--------------------------+-------------------+---------------------+
So far, i have this query, but id doesn't returns correct record..
SELECT po.purchase_order_id, SUM(pod.ordered_quantity) AS Sum_of_ordered_quantity, SUM(dor.recieved_quantity) AS Sum_of_recieved_quantity
FROM purchase_order AS po
INNER JOIN purchase_order_detail AS pod ON po.purchase_order_id = pod.purchase_order_id
INNER JOIN delivery_order AS dor ON dor.purchase_order_detail_id = pod.purchase_order_detail_id
GROUP BY po.purchase_order_id
it returns this,
+-------------------+-------------------------+--------------------------+
| purchase_order_id | Sum_of_ordered_quantity | Sum_of_received_quantity |
+-------------------+-------------------------+--------------------------+
| 1 | 300 | 150 |
| 2 | 1500 | 500 |
+-------------------+-------------------------+--------------------------+
you can see in the question that , purchase_order_id 1 has 200 ordered quantity and 150 received quantity while purchase_order_id 2 has 500 ordered_quantity and 500 received quantity.
Please try this code:
SELECT po.purchase_order_id,
SUM(pod.ordered_quantity) AS Sum_of_ordered_quantity,
(SELECT `mySelect`.`desired_sum` FROM
(SELECT B.`purchase_order_id` AS myID, SUM( `A`.`recieved_quantity` ) AS desired_sum
FROM `delivery_order` AS A
LEFT JOIN `purchase_order_detail` AS B ON A.purchase_order_detail_id = B.purchase_order_detail_id
GROUP BY B.`purchase_order_id` ) AS mySelect
WHERE `mySelect`.`myID` = `po`.`purchase_order_id`) AS Sum_of_received_quantity
FROM purchase_order AS po
INNER JOIN purchase_order_detail AS pod ON po.purchase_order_id = pod.purchase_order_id
GROUP BY po.purchase_order_id
This is usual while doing aggregate sum function with multiple many-to-many tables with different joining condition.
One way is to use correlated subquery to get the aggregate value and then do the join. Something as
select
po.purchase_order_id,
pod.Sum_of_ordered_quantity,
do.Sum_of_received_quantity
from purchase_order po
join
(
select purchase_order_id,sum(ordered_quantity) as Sum_of_ordered_quantity
from purchase_order_detail
group by purchase_order_id
)pod on pod.purchase_order_id = po.purchase_order_id
join
(
select
t1.purchase_order_id,
sum(t2.recieved_quantity) as Sum_of_received_quantity
from purchase_order_detail t1
join delivery_order t2 on t1.purchase_order_detail_id = t2.purchase_order_detail_id
group by t1.purchase_order_id
)do on do.purchase_order_id = po.purchase_order_id
DEMO