Combine two SQL Queries efficiently - mysql

I have two Queries:
1)
SELECT COUNT(*) AS total, COUNT(supporter) AS done FROM Supports;
2)
SELECT supporter, COUNT(supporter) AS amount FROM Supports
GROUP BY supporter ORDER BY amount DESC LIMIT 1;
How can I efficiently combine them?
This is how the Table looks like:
+-----------------------------+
| id | name | supporter |
+-----------------------------+
| 1 | user1 | sup1 |
| 2 | user1 | sup2 |
| 3 | user1 | NULL |
| 4 | user2 | sup1 |
| 5 | user2 | sup3 |
+-----------------------------+

Since you want the total, you'll have to use a subquery to combine into one query. Include it in the FROM clause.
SELECT supporter, COUNT(supporter) AS amount, total, done
FROM Supports,
(SELECT COUNT(*) AS total, COUNT(supporter) AS done FROM Supports) totals
GROUP BY supporter
ORDER BY amount DESC
LIMIT 1;

I believe this is what you are looking for:
SELECT
(SELECT COUNT(*) FROM Supports) as total,
(SELECT COUNT(supporter) FROM Supports) as done,
supporter,
COUNT(*) AS amount
FROM Supports
GROUP BY supporter
ORDER BY amount;
Results looks like this: http://sqlfiddle.com/#!9/9e4ee/9
total done supporter amount
5 4 sup3 1
5 4 sup2 1
5 4 NULL 1
5 4 sup1 2

SELECT a.total, a.done, b.supporter, b.amount
( SELECT COUNT(*) AS total,
COUNT(supporter) AS done
FROM Supports
) AS a
JOIN
( SELECT supporter,
COUNT(supporter) AS amount
FROM Supports
GROUP BY supporter
ORDER BY amount DESC
LIMIT 1
) AS b;

Related

Group all rows after nth row together

I have the current table:
+----------+-------+
| salesman | sales |
+----------+-------+
| 1 | 142 |
| 2 | 120 |
| 3 | 176 |
| 4 | 140 |
| 5 | 113 |
| 6 | 137 |
| 7 | 152 |
+----------+-------+
I would like to make a query to retrieve the 3 top salesman, and an "Other" column, that would be the sum of everyone else. The expected output would be:
+----------+-------+
| salesman | sales |
+----------+-------+
| 3 | 176 |
| 7 | 152 |
| 1 | 142 |
| Others | 510 |
+----------+-------+
I am using MySQL, and I am experienced about it, but i can't imagine a way of doing this kind of GROUP BY.
A tried UNION with 2 SELECT, one for the top 3 salesman and another select for the "Others", but I couldn't figure a way of excluding the top 3 from the 2nd SELECT
You can do this by LEFT JOINing your table to a list of the top 3 salesmen, and then grouping on the COALESCEd salesman number from the top 3 table (which will be NULL if the salesman is not in the top 3).
SELECT COALESCE(top.sman, 'Others') AS saleman,
SUM(sales) AS sales
FROM test
LEFT JOIN (SELECT salesman AS sman
FROM test
ORDER BY sales DESC
LIMIT 3) top ON top.sman = test.salesman
GROUP BY saleman
ORDER BY saleman = 'Others', sales DESC
Output:
saleman sales
3 176
7 152
1 142
Others 510
Demo on dbfiddle
Using UNION, ORDER BY, LIMIT, OFFSET AND GROUP BY statements you should do the trick:
SELECT salesman, sales
FROM t
ORDER BY sales DESC LIMIT 3
UNION
SELECT 'Others', SUM(sales)
FROM (SELECT salesman, sales
FROM t
ORDER BY sales DESC LIMIT 3, 18446744073709551615) AS tt;
The big number at the end is the way to apply limit until the end of the table, as suggested here
This is a pain in MySQL:
(select salesman, count(*) as cnt
from t
group by salesman
order by count(*), salesman
limit 3
) union all
(select 'Others', count(*)
from t left join
(select salesman, count(*) as cnt
from t
group by salesman
order by count(*)
limit 3
) t3
on t3.salesman = t.salesman
where t3.salesman is null
);
This should be the fastest one if appropriate indexes are present:
(
SELECT salesman, sales
FROM t
ORDER BY sales DESC
LIMIT 3
)
UNION ALL
(
SELECT 'Other', SUM(sales) - (
SELECT SUM(sales)
FROM (
SELECT sales
FROM t
ORDER BY sales DESC
LIMIT 3
) AS top3
)
FROM t
)
ORDER BY CASE WHEN salesman = 'Other' THEN NULL ELSE sales END DESC
this will work:
select salesman,sales from tablename a where a.salesman in (3,7,1)
union all
select 'others' as others,sum(a.sales) as sum_of_others from tablename a where
a.salesman not in (3,7,1) group by others;
check https://www.db-fiddle.com/f/73GjFXL3KsZsYnN26g3rS2/0

Can't get appropriate values from query?

I want to list companyIds and with the mostly occur commentable type (0,1,2).
This is subquery
select a.companyId, a.commentable, count(1) _count
from article a
group by a.companyId, a.commentable
| companyId | commentable | _count |
|-----------|-------------|--------|
| 1 | 0 | 1 |
| 1 | 1 | 1 |
| 2 | 0 | 7759 |
| 2 | 1 | 7586 |
| 2 | 2 | 7856 |
| 3 | 0 | 7828 |
| 3 | 1 | 7866 |
| 3 | 2 | 7706 |
| 4 | 0 | 7851 |
| 4 | 1 | 7901 |
| 4 | 2 | 7738 |
| 5 | 0 | 7775 |
| 5 | 1 | 7884 |
| 5 | 2 | 7602 |
| 25 | 0 | 7888 |
| 25 | 1 | 7939 |
| 25 | 2 | 7784 |
For example above
Most commentable type occur for companyId=4 is 7901 and commentable type for that is 1. In below query , i see 4-0-7901, but i expected 4-1-7901
SELECT x.companyId, x.commentable, MAX(x._count) _count
FROM
( SELECT a.companyId, a.commentable, COUNT(1) _count
FROM article a
GROUP BY a.companyId, a.commentable
) AS X
GROUP BY x.companyId;
companyId commentable _count
1 0 1
2 0 7856
3 0 7866
4 0 7901
5 0 7884
25 0 7939
Expected result
companyId commentable _count
1 0 1
2 2 7856
3 1 7866
4 1 7901
5 1 7884
25 1 7939
I dont understand 'why is all commentable column is '0' .
You need a big ugly join here. In the query below, you may view the GROUP BY query on the company and comment type the base unit of work. This query appears as itself, aliased as t1. In alias t2, we subquery and aggregate only by commentable, to find the max count for each such comment type. This, we join back to t1 to restrict only the company having the max count.
SELECT
t1.companyId,
t1.commentable,
t1.cnt
FROM
(
SELECT companyId, commentable, COUNT(*) cnt
FROM article
GROUP BY companyId, commentable
) t1
INNER JOIN
(
SELECT companyId, MAX(cnt) max_cnt
FROM
(
SELECT companyId, commentable, COUNT(*) cnt
FROM article
GROUP BY companyId, commentable
) t
GROUP BY companyId
) t2
ON t1.companyId = t2.companyId AND t1.cnt = t2.max_cnt;
By the way, things get somewhat nicer in MySQL 8+, where we can take advantage of analytic functions:
WITH cte AS (
SELECT companyId, commentable, COUNT(*) cnt,
ROW_NUMBER() OVER (PARTITION BY commentable ORDER BY COUNT(*) DESC) rn
FROM article
GROUP BY companyId, commentable
)
SELECT companyId, commentable, cnt
FROM cte
WHERE rn = 1;
You can do this using a having clause:
SELECT a.companyId, a.commentable, COUNT(*) as _count
FROM article a
GROUP BY a.companyId, a.commentable
HAVING COUNT(*) = (SELECT COUNT(*)
FROM article a2
WHERE a2.companyId = a.companyId
GROUP BY a2.commentable
ORDER BY COUNT(*) DESC
LIMIT 1
);
In the event of ties, you will get multiple rows. If you want only one row per company, you can instead use commentable for the comparison in the HAVING:
SELECT a.companyId, a.commentable, COUNT(*) as _count
FROM article a
GROUP BY a.companyId, a.commentable
HAVING a.commentable = (SELECT a2.commentable
FROM article a2
WHERE a2.companyId = a.companyId
GROUP BY a2.commentable
ORDER BY COUNT(*) DESC
LIMIT 1
);
As others have mentioned, your problem is the mis-use of GROUP BY. The unaggregated columns in the SELECT need to match the GROUP BY keys -- and vice versa.
Cause commentable is not one of group by columns. In this case, with ONLY_FULL_GROUP_BY disabled, MySQL is free to choose any one value for this column.
From MySQL doc
If ONLY_FULL_GROUP_BY is disabled, a MySQL extension to the standard SQL use of GROUP BY permits the select list, HAVING condition, or ORDER BY list to refer to nonaggregated columns even if the columns are not functionally dependent on GROUP BY columns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic, which is probably not what you want.

How can I identify if a certain row is the last by using an ID in MySQL

Sorry to confuse you about my title. I am building an auction system and I am having a difficulty in getting the user's winning item.
Example I have a table like this:
the columns are:
id, product_id, user_id, status, is_winner, info, bidding_price, bidding_date
here's my sql fiddle:
http://sqlfiddle.com/#!9/7097d/1
I want to get every user's item that they already win. So I need to identify if they are the last who bid in that item.
I need to filter it using a user_id.
If I do a query like this:
SELECT MAX(product_id) AS product_id FROM auction_product_bidding
WHERE user_id = 3;
it will get only the product_id that is 12 and the product_id of 9 did not get. Product ID 9 is also that last bid of the user_id 3.
Can you help me? I hope you got my point. Thanks. Sorry if my question a little bit confusing.
According to your question, seems 11 is also what you want, try this query:
SELECT apd.product_id
FROM auction_product_bidding apd
JOIN (
SELECT MAX(bidding_date) AS bidding_date, product_id
FROM auction_product_bidding
GROUP BY product_id
) t
ON apd.product_id = t.product_id
AND apd.bidding_date = t.bidding_date
WHERE apd.user_id = 3;
Check Demo Here
select id,product_id,user_id,status,is_winner,info,bidding_price,bidding_date,rank
from
( SELECT apb.*,
greatest(#rank:=if(product_id=#prodGrp,#rank+1,1),-1) as rank,
#prodGrp:=product_id as dummy
FROM auction_product_bidding apb
cross join (select #prodGrp:=-1,#rank:=0) xParams
order by product_id,bidding_date DESC
) xDerived
where user_id=3 and rank=1;
That user won 9,11,12
+----+------------+---------+--------+-----------+------+---------------+---------------------+------+
| id | product_id | user_id | status | is_winner | info | bidding_price | bidding_date | rank |
+----+------------+---------+--------+-----------+------+---------------+---------------------+------+
| 60 | 9 | 3 | | 0 | | 75000.00 | 2016-08-02 16:31:23 | 1 |
| 59 | 11 | 3 | | 0 | | 15000.00 | 2016-08-02 12:04:16 | 1 |
| 68 | 12 | 3 | | 0 | | 18000.00 | 2016-08-10 09:20:01 | 1 |
+----+------------+---------+--------+-----------+------+---------------+---------------------+------+
SELECT product_id FROM auction_product_bidding where bidding_price= any
(select max(bidding_price) from auction_product_bidding group by product_id)
and user_id='3';
select * from
(select product_id,user_id,max(bidding_price) from
(select * from auction_product_bidding order by bidding_price desc) a
group by product_id) b
where user_id=3;
Answer:
product_id user_id max(bidding_price)
9 3 75000
11 3 15000
12 3 18000
An idea could be to sort the table desc by date and select every distinct row by product_id and customer_id. Something like
SELECT DISTINCT prod_id, user_id FROM (
SELECT * FROM auction_product_bidding ORDER BY date DESC
)
You want everything that bids last in 3, is it right ?

SUM a pair of COUNTs from two tables based on a time variable

Been searching for an answer to this for the better part of an hour without much luck. I have two regional tables laid out with the same column names and I can put out a result list for either table based on the following query (swap Table2 for Table1):
SELECT Table1.YEAR, FORMAT(COUNT(Table1.id),0) AS Total
FROM Table1
WHERE Table1.variable='Y'
GROUP BY Table1.YEAR
Ideally I'd like to get a result that gives me a total sum of the counts by year, so instead of:
| REGION 1 | | REGION 2 |
| YEAR | Total | | YEAR | Total |
| 2010 | 5 | | 2010 | 1 |
| 2009 | 2 | | 2009 | 3 |
| | | | 2008 | 4 |
I'd have:
| MERGED |
| YEAR | Total |
| 2010 | 6 |
| 2009 | 5 |
| 2008 | 4 |
I've tried a variety of JOINs and other ideas but I think I'm caught up on the SUM and COUNT issue. Any help would be appreciated, thanks!
SELECT `YEAR`, FORMAT(SUM(`count`), 0) AS `Total`
FROM (
SELECT `Table1`.`YEAR`, COUNT(*) AS `count`
WHERE `Table1`.`variable` = 'Y'
GROUP BY `Table1`.`YEAR`
UNION ALL
SELECT `Table2`.`YEAR`, COUNT(*) AS `count`
WHERE `Table2`.`variable` = 'Y'
GROUP BY `Table2`.`YEAR`
) AS `union`
GROUP BY `YEAR`
You should use an UNION:
SELECT
t.YEAR,
COUNT(*) as TOTAL
FROM (
SELECT *
FROM Table1
UNION ALL
SELECT *
FROM Table2
) t
WHERE t.variable='Y'
GROUP BY t.YEAR;
Select year, sum(counts) from (
SELECT Table1.YEAR, FORMAT(COUNT(Table1.id),0) AS Total
FROM Table1
WHERE Table1.variable='Y'
GROUP BY Table1.YEAR
UNION ALL
SELECT Table2.YEAR, FORMAT(COUNT(Table2.id),0) AS Total
FROM Table2
WHERE Table2.variable='Y'
GROUP BY Table2.YEAR ) GROUP BY year
To improve upon Shehzad's answer:
SELECT YEAR, FORMAT(SUM(counts),0) AS total FROM (
SELECT Table1.YEAR, COUNT(Table1.id) AS counts
FROM Table1
WHERE Table1.variable='Y'
GROUP BY Table1.YEAR
UNION ALL
SELECT Table2.YEAR, COUNT(Table2.id) AS counts
FROM Table2
WHERE Table2.variable='Y'
GROUP BY Table2.YEAR ) AS newTable GROUP BY YEAR

Sort data before using GROUP BY?

I have read that grouping happens before ordering, is there any way that I can order first before grouping without having to wrap my whole query around another query just to do this?
Let's say I have this data:
id | user_id | date_recorded
1 | 1 | 2011-11-07
2 | 1 | 2011-11-05
3 | 1 | 2011-11-06
4 | 2 | 2011-11-03
5 | 2 | 2011-11-06
Normally, I'd have to do this query in order to get what I want:
SELECT
*
FROM (
SELECT * FROM table ORDER BY date_recorded DESC
) t1
GROUP BY t1.user_id
But I'm wondering if there's a better solution.
Your question is somewhat unclear but I have a suspicion what you really want is not any GROUP aggregates at all, but rather ordering by date first, then user ID:
SELECT
id,
user_id,
date_recorded
FROM tbl
ORDER BY date_recorded DESC, user_id ASC
Here would be the result. Note reordering by date_recorded from your original example
id | user_id | date_recorded
1 | 1 | 2011-11-07
3 | 1 | 2011-11-06
2 | 1 | 2011-11-05
5 | 2 | 2011-11-06
4 | 2 | 2011-11-03
Update
To retrieve the full latest record per user_id, a JOIN is needed. The subquery (mx) locates the latest date_recorded per user_id, and that result is joined to the full table to retrieve the remaining columns.
SELECT
mx.user_id,
mx.maxdate,
t.id
FROM (
SELECT
user_id,
MAX(date_recorded) AS maxdate
FROM tbl
GROUP BY user_id
) mx JOIN tbl t ON mx.user_id = t.user_id AND mx.date_recorded = t.date_recorded
Iam just using the technique
"Using order clause before group by inserting it in group_concat clause"
SELECT SUBSTRING_INDEX(group_concat(cast(id as char)
ORDER BY date_recorded desc),',',1),
user_id,
SUBSTRING_INDEX(group_concat(cast(`date_recorded` as char)
ORDER BY `date_recorded` desc),',',1)
FROM data
GROUP BY user_id