Getting highest calculated score of GROUP BY in mysql - mysql

I'm trying to retrieve the best suited price for a product in each quantity depending on the customer and/or his customer group. To do so, I use a weight based system: the matching customer group is more important than the matching customer, so if two rows collide, we should get the row corresponding to the customer group id.
Here's an example:
Customer n°1 is part of Customer group n°2
Product prices:
A - 90€ for customer n°1 (when buying at least 2 of the same product)
B - 80€ for customer group n°2 (when buying at least 2 of the same product)
So the price shown to the customer n°1 should be 80€
He's my query:
SELECT
MAX(IF(t.customer_id = 1, 10, 0) + IF(t.customer_group_id = 1, 100, 0)) as score,
t.*
FROM tierprice t
WHERE t.product_variant_id = 110
AND (t.customer_id = 1 OR t.customer_id IS NULL)
AND (t.customer_group_id = 1 OR t.customer_group_id IS NULL)
GROUP BY t.product_variant_id, t.qty
The problem I'm having is that the correct score is shown in the result row (here: 100), but the row for the given score is not correct. I'm guessing it has something to do with the MAX in the SELECT and the GROUP BY, but I don't know how to assign the score to the row, and then take the highest.
Here's a fiddle :
CREATE TABLE `tierprice` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`product_variant_id` int(11) DEFAULT NULL,
`customer_group_id` int(11) DEFAULT NULL,
`price` int(11) NOT NULL,
`qty` int(11) NOT NULL,
`customer_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `no_duplicate_prices` (`qty`,`product_variant_id`,`customer_group_id`),
KEY `IDX_BA5254F8A80EF684` (`product_variant_id`),
KEY `IDX_BA5254F8D2919A68` (`customer_group_id`),
KEY `IDX_BA5254F89395C3F3` (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `tierprice` (`id`, `product_variant_id`, `customer_group_id`, `price`, `qty`, `customer_id`)
VALUES
(1, 110, NULL, 8000, 2, 1),
(2, 110, 1, 7000, 2, NULL),
(3, 110, 1, 6000, 5, NULL),
(4, 110, NULL, 5000, 5, 1),
(5, 111, 1, 8000, 2, NULL),
(6, 111, NULL, 6000, 2, 1),
(7, 111, 1, 7000, 6, NULL),
(8, 111, NULL, 5000, 6, 1);
http://sqlfiddle.com/#!9/7bc0d9/2
The price ids that should come out in the result should be ID 2 & ID 3.
Thank you for your help.

Provided query is not a valid query from SQL standard's perspective:
SELECT
MAX(IF(t.customer_id = 1, 10, 0) + IF(t.customer_group_id = 1, 100, 0)) as score,
t.*
FROM tierprice t
WHERE t.product_variant_id = 110
AND (t.customer_id = 1 OR t.customer_id IS NULL)
AND (t.customer_group_id = 1 OR t.customer_group_id IS NULL)
GROUP BY t.product_variant_id, t.qty;
Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 't.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Related: Group by clause in mySQL and postgreSQL, why the error in postgreSQL?
It could be rewritten using windowed functions(MySQL 8.0 and above):
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER(PARTITION BY product_variant_id, qty
ORDER BY IF(t.customer_id=1,10,0)+IF(t.customer_group_id=1,100,0) DESC) AS rn
FROM tierprice t
WHERE t.product_variant_id = 110
AND (t.customer_id = 1 OR t.customer_id IS NULL)
AND (t.customer_group_id = 1 OR t.customer_group_id IS NULL)
)
SELECT *
FROM cte
WHERE rn = 1;
db<>fiddle demo

The only valid columns that your query can return are product_variant_id, qty, which you use in GROUP BY clause, and the aggregated column score.
Because of t.* you get all the columns of the table but the values chosen are nondeterministic, for the other columns, as it is explained in MySQL Handling of GROUP BY.
What you can do is join your query to the table like this:
SELECT t.*
FROM tierprice t
INNER JOIN (
SELECT product_variant_id, qty,
MAX(IF(customer_id = 1, 10, 0) + IF(customer_group_id = 1, 100, 0)) as score
FROM tierprice
WHERE product_variant_id = 110
AND (customer_id = 1 OR customer_id IS NULL)
AND (customer_group_id = 1 OR customer_group_id IS NULL)
GROUP BY product_variant_id, qty
) g ON g.product_variant_id = t.product_variant_id
AND g.qty = t.qty
AND g.score = IF(t.customer_id = 1, 10, 0) + IF(t.customer_group_id = 1, 100, 0)
WHERE (t.customer_id = 1 OR t.customer_id IS NULL)
AND (t.customer_group_id = 1 OR t.customer_group_id IS NULL)
See the demo.
Results:
> id | product_variant_id | customer_group_id | price | qty | customer_id
> -: | -----------------: | ----------------: | ----: | --: | ----------:
> 2 | 110 | 1 | 7000 | 2 | null
> 3 | 110 | 1 | 6000 | 5 | null

Related

Find DISTINCT LAST record with SQL LEFT JOIN

I'm running MySQL 5.6.
I have two related tables:
CREATE TABLE Cars (
id INT NOT NULL AUTO_INCREMENT,
plate VARCHAR(16) NOT NULL,
flag TINYINT,
PRIMARY KEY(id)
)
and:
CREATE TABLE Rents (
id INT NOT NULL AUTO_INCREMENT,
out_date DATE NOT NULL,
in_date DATE,
car_id INT,
FOREIGN KEY (car_id) REFERENCES Cars(id),
PRIMARY KEY(id)
)
I can have multiple rents for each car (0 to many).
I need to select all vehicles in table Cars (with flag = 1) along with their status i.e. I need to know if each car is currently unavailable (only out_date is filled) or availabe (out_date and in_date filled) of course also vehicles without any rents are to be considered available.
The result set need to include out_date and in_date values [Update 17/07/2022].
I tought to use something like:
SELECT
*,
IF(Rents.in_date IS NOT NULL AND Rents.out_date IS NOT NULL, 1, IF(Rents.id IS NULL, 1, 0)) AS status
FROM Cars
LEFT JOIN Rents ON Cars.id = Rent.Car_id WHERE Cars.Flag = 1
but this of course will just return all the rows with positive flag match and a status evaluation (0 unavailable, 1 available):
id | plate | flag | id | out_date | in_date | car_id | status
---------------------------------------------------------------------
'1', 'FA787MX', '1', '1', '2022-07-14', '2022-07-15', '1', '1'
'1', 'FA787MX', '1', '2', '2022-07-16', NULL, '1', '0'
'3', 'AB124DF', '1', '4', '2022-07-13', '2022-07-14', '3', '1'
'4', 'CC666VC', '1', NULL, NULL, NULL, NULL, '1'
'5', 'GG435ED', '1', '5', '2022-07-16', NULL, '5', '0'
While I need to have this (edited 17/07/2022):
'1', 'FA787MX', '1', '2', '2022-07-16', NULL, '1', '0'
'3', 'AB124DF', '1', '4', '2022-07-13', '2022-07-14', '3', '1'
'4', 'CC666VC', '1', NULL, NULL, NULL, NULL, '1'
'5', 'GG435ED', '1', '5', '2022-07-16', NULL, '5', '0'
i.e. only the second row of FA787MX car should be mantained since it's the most recent out_date value (no matter if it's id is higher or lower).
For the sake of completeness: There is no guarantee that rental ids will be kept consistent with their rental history. In other words you cannot be sure that for a given car the rental where in_date = NULL is the correct one but you should compare them by out_date value.
Data sample:
INSERT INTO `Cars` (`id`, `plate`, `flag`) VALUES (1, 'FA787MX', 1);
INSERT INTO `Cars` (`id`, `plate`, `flag`) VALUES (2, 'EX431YY', 0);
INSERT INTO `Cars` (`id`, `plate`, `flag`) VALUES (3, 'AB124DF', 1);
INSERT INTO `Cars` (`id`, `plate`, `flag`) VALUES (4, 'CC666VC', 1);
INSERT INTO `Cars` (`id`, `plate`, `flag`) VALUES (5, 'GG435ED', 1);
INSERT INTO `Rents` (`id`, `out_date`, `in_date`, `car_id`) VALUES (1, '2022-07-14', '2022-07-15', 1);
INSERT INTO `Rents` (`id`, `out_date`, `in_date`, `car_id`) VALUES (2, '2022-07-16', NULL, 1);
INSERT INTO `Rents` (`id`, `out_date`, `in_date`, `car_id`) VALUES (3, '2022-07-16', NULL, 2);
INSERT INTO `Rents` (`id`, `out_date`, `in_date`, `car_id`) VALUES (4, '2022-07-13', '2022-07-14', 3);
INSERT INTO `Rents` (`id`, `out_date`, `in_date`, `car_id`) VALUES (5, '2022-07-16', NULL, 5);
One option is to join to find only those rentals that are still outstanding (in_date IS NULL). That will drop the old rentals having in_date not null.
Based on the updated requirements, there are a few ways to do it. One is a simple outer join to find the most recent rental per car to obtain the corresponding in_date as well...
MySQL 5.6 fiddle
SELECT Cars.*
, Rents.out_date
, Rents.in_date
, Rents.id IS NULL OR Rents.in_date IS NOT NULL AS status_final
FROM Cars
LEFT JOIN Rents
ON Cars.id = Rents.Car_id
LEFT JOIN Rents AS r2
ON Rents.out_date < r2.out_date
AND Rents.Car_id = r2.Car_id
WHERE Cars.Flag = 1
AND r2.Car_id IS NULL
ORDER BY Cars.id
;
The result:
id
plate
flag
out_date
in_date
status_final
1
FA787MX
1
2022-07-16
0
3
AB124DF
1
2022-07-13
2022-07-14
1
4
CC666VC
1
1
5
GG435ED
1
2022-07-16
0
Based on the original requirements: Try this (fiddle):
SELECT Cars.*
, Rents.in_date
, CASE WHEN in_date IS NOT NULL OR Rents.id IS NULL THEN 1 ELSE 0 END AS status_final
FROM Cars
LEFT JOIN Rents
ON Cars.id = Rents.Car_id
AND in_date IS NULL
WHERE Cars.Flag = 1
;
and if the results contain only those with in_date IS NULL, this reduces to:
SELECT Cars.*
, out_date
, Rents.in_date
, Rents.id IS NULL AS status_final
FROM Cars
LEFT JOIN Rents
ON Cars.id = Rents.Car_id
AND in_date IS NULL
WHERE Cars.Flag = 1
;
Result:
id
plate
flag
out_date
in_date
status_final
1
FA787MX
1
2022-07-16
0
3
AB124DF
1
1
4
CC666VC
1
1
5
GG435ED
1
2022-07-16
0
If your version of MySql is 8.0+ use ROW_NUMBER() window function to pick the latest row for each car in Rents:
SELECT c.*, r.*,
r.out_date IS NULL OR r.in_date IS NOT NULL status
FROM Cars c
LEFT JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY car_id ORDER BY out_date DESC) rn
FROM Rents
) r ON r.car_id = c.id AND r.rn = 1
WHERE c.flag = 1;
For previous versions use NOT EXISTS:
SELECT c.*, r.*,
r.out_date IS NULL OR r.in_date IS NOT NULL status
FROM Cars c
LEFT JOIN (
SELECT r1.*
FROM Rents r1
WHERE NOT EXISTS (
SELECT *
FROM Rents r2
WHERE r2.car_id = r1.car_id AND r2.out_date > r1.out_date
)
) r ON r.car_id = c.id
WHERE c.flag = 1;
See the demo.
If you imagine the result of your query as a table, you can easily write a query that would give you what you need (the subquery is just yours with the select spelled out to give a unique column name to the second id column, as it seemed useful - the only way to uniquely identify a row):
SELECT MAX(rent_id) FROM (
SELECT
Cars.id as id,
plate,
flag,
Rents.id as rent_id,
out_date,
in_date,
car_id,
IF(Rents.in_date IS NOT NULL AND Rents.out_date IS NOT NULL, 1, IF(Rents.id IS NULL, 1, 0)) AS status
FROM Cars
LEFT JOIN Rents ON Cars.id = Rents.car_id WHERE Cars.Flag = 1
) as rental_status
WHERE status = 0
GROUP BY car_id;
Which tells you which rows are interesting:
+--------------+
| MAX(rent_id) |
+--------------+
| 2 |
| 5 |
+--------------+
Now you can use a join to return the results of your initial query only for the interesting rows. To avoid having to spell out that query all over again, MySQL 8 has a way to stash the results of your core query and use it like a table:
WITH
status_data AS (
SELECT
Cars.id as id,
plate,
flag,
Rents.id as rent_id,
out_date,
in_date,
car_id,
IF(Rents.in_date IS NOT NULL AND Rents.out_date IS NOT NULL, 1, IF(Rents.id IS NULL, 1, 0)) AS status
FROM Cars
LEFT JOIN Rents ON Cars.id = Rents.car_id WHERE Cars.Flag = 1
)
SELECT * from status_data
JOIN (
SELECT MAX(rent_id) as rent_id FROM status_data
WHERE status = 0
GROUP BY car_id
) as ids using(rent_id);
Giving the result:
+---------+----+---------+------+------------+---------+--------+--------+
| rent_id | id | plate | flag | out_date | in_date | car_id | status |
+---------+----+---------+------+------------+---------+--------+--------+
| 2 | 1 | FA787MX | 1 | 2022-07-16 | NULL | 1 | 0 |
| 5 | 5 | GG435ED | 1 | 2022-07-16 | NULL | 5 | 0 |
+---------+----+---------+------+------------+---------+--------+--------+

Displayed values are not what they should be

There are 2 tables ost_ticket and ost_ticket_action_history.
create table ost_ticket(
ticket_id int not null PRIMARY KEY,
created timestamp,
staff bool,
status varchar(50),
city_id int
);
create table ost_ticket_action_history(
ticket_id int not null,
action_id int not null PRIMARY KEY,
action_name varchar(50),
started timestamp,
FOREIGN KEY(ticket_id) REFERENCES ost_ticket(ticket_id)
);
In the ost_ticket_action_history table the data is:
INSERT INTO newdb.ost_ticket_action_history (ticket_id, action_id, action_name, started) VALUES (1, 1, 'Consultation', '2022-01-06 18:30:29');
INSERT INTO newdb.ost_ticket_action_history (ticket_id, action_id, action_name, started) VALUES (2, 2, 'Bank Application', '2022-02-06 18:30:45');
INSERT INTO newdb.ost_ticket_action_history (ticket_id, action_id, action_name, started) VALUES (3, 3, 'Consultation', '2022-05-06 18:42:48');
In the ost_ticket table the data is:
INSERT INTO newdb.ost_ticket (ticket_id, created, staff, status, city_id) VALUES (1, '2022-04-04 18:26:41', 1, 'open', 2);
INSERT INTO newdb.ost_ticket (ticket_id, created, staff, status, city_id) VALUES (2, '2022-05-05 18:30:48', 0, 'open', 3);
INSERT INTO newdb.ost_ticket (ticket_id, created, staff, status, city_id) VALUES (3, '2022-04-06 18:42:53', 1, 'open', 4);
My task is to get the conversion from the “Consultation” stage to the “Bank Application” stage broken down by months (based on the start date of the “Bank Application” stage).Conversion is calculated according to the following formula: (number of applications with the “Bank Application” stage / number of applications with the “Consultation” stage) * 100%.
My request is like this:
select SUM(action_name='Bank Application')/SUM(action_name='Consultation') * 2 as 'Conversion' from ost_ticket_action_history JOIN ost_ticket ot on ot.ticket_id = ost_ticket_action_history.ticket_id where status = 'open' and created > '2020 -01-01 00:00:00' group by action_name,started having action_name = 'Bank Application';
As a result I get:
Another query:
SELECT
SUM(CASE
WHEN b.ticket_id IS NOT NULL THEN 1
ELSE 0
END) / COUNT(*) conversion,
YEAR(a.started) AS 'year',
MONTH(a.started) AS 'month'
FROM
ost_ticket_action_history a
LEFT JOIN
ost_ticket_action_history b ON a.ticket_id = b.ticket_id
AND b.action_name = 'Bank Application'
WHERE
a.action_name = 'Consultation'
AND a.status = 'open'
AND a.created > '2020-01-01 00:00:00'
GROUP BY YEAR(a.started) , MONTH(a.started)
I apologize if I didn't write very clearly. Please explain what to do.
Like I explained in my comment, you exclude rows with your having clause.
I will show you in the next how to debug.
First check what the raw result of the select query is.
As you see, when you remove the GROUP BY and see what you actually get is only 1 row with bank application, because the having clause excludes all other rows
SELECT
*
FROM
ost_ticket_action_history
JOIN
ost_ticket ot ON ot.ticket_id = ost_ticket_action_history.ticket_id
WHERE
status = 'open'
AND created > '2020-01-01 00:00:00'
GROUP BY
action_name, started
HAVING
action_name = 'Bank Application';
Output:
ticket_id
action_id
action_name
started
ticket_id
created
staff
status
city_id
2
2
Bank Application
2022-02-06 18:30:45
2
2022-05-05 18:30:48
0
open
3
Second step, see what the result set is without calculating anything.
As you can see you make a division with 0, what you have learned in school, is forbidden, hat is why you have as result set NULL
SELECT
SUM(action_name = 'Bank Application')
#/
,SUM(action_name = 'Consultation') * 2 AS 'Conversion'
FROM
ost_ticket_action_history
JOIN
ost_ticket ot ON ot.ticket_id = ost_ticket_action_history.ticket_id
WHERE
status = 'open'
AND created > '2020-01-01 00:00:00'
GROUP BY action_name , started
HAVING action_name = 'Bank Application';
SUM(action_name = 'Bank Application') | Conversion
------------------------------------: | ---------:
1 | 0
db<>fiddle here
#Third what you can do exclude a division with 0, here i didn't remove all othe rows as this is only for emphasis
SELECT
SUM(action_name = 'Bank Application')
/
SUM(action_name = 'Consultation') * 2 AS 'Conversion'
FROM
ost_ticket_action_history
JOIN
ost_ticket ot ON ot.ticket_id = ost_ticket_action_history.ticket_id
WHERE
status = 'open'
AND created > '2020-01-01 00:00:00'
GROUP BY action_name , started
HAVING SUM(action_name = 'Consultation') > 0;
| Conversion |
| ---------: |
| 0.0000 |
| 0.0000 |
db<>fiddle here
Final words,
If you get a strange result, simply go back remove everything that doesn't matter and try to get all values, so hat you can check your math

Get summary grouped by category with three tables on mysql

category
---------------------------
id_category primary key
category
id_user foreign key
counterpart
---------------------------
id_counterpart primary key
counterpart
id_category foreign key
id_user foreign key
transaction
---------------------------
transaction primary key
date
id_counterpart foreign key
amount
id_card foreign key
id_user foreign key
Hello,
I have thoses table on mysql database and i want to have summary of each category (with 0 if there is any transaction) by month and year based on id_user.
I tried this command to have grouped by counterpart and it works but cannot reach when i add category and group by id_category.
select counterpart, s2.total from counterpart as s1
left join (select coalesce(sum(amount),0) as total, id_counterpart from transaction where year(date) = 2019 and month(date) = 7 and id_user = 2 group by id_counterpart) as s2
on s1.id_counterpart = s2.id_counterpart
left join category on s1.id_category = category.id_category
group by counterpart;
Do you have any idea to do that ? Else, i will do with php.
Thank you.
Edit : Add example
INSERT INTO `category` (`id_category`, `category`, `id_user`) VALUES
(1, 'cat_a', 1),
(2, 'cat_b', 1),
(3, 'cat_c', 1);
INSERT INTO `counterpart` (`id_counterpart`, `counterpart`, `id_category`, `id_user`) VALUES
(1, 'cp_a', 1, 1),
(2, 'cp_b', 2, 1),
(3, 'cp_c', 2, 1);
INSERT INTO `transaction` (`id_transaction`, `date`, `id_counterpart`, `amount`, `id_card`, `id_user`) VALUES
(1, '2019-07-01 00:00:00', 1, 400.00, 2, 1),
(2, '2019-07-01 00:00:00', 1, -24.95, 2, 1),
(3, '2019-07-31 00:00:00', 2, -20.04, 2, 1);
(4, '2019-07-30 00:00:00', 2, -1.00, 2, 1);
(5, '2019-07-29 00:00:00', 3, -2.00, 2, 1);
(6, '2019-07-28 00:00:00', 1, -3.00, 2, 1);
(7, '2019-07-27 00:00:00', 3, 2.00, 2, 1);
(8, '2019-07-26 00:00:00', 2, 5.00, 2, 1);
On july 2019 i want to have this, for user 1 :
cat_a 372.05
cat_b 16.04
cat_c 0.00
Join the tables and then group by category:
select c.category, coalesce(sum(t.amount), 0) total
from category c
left join counterpart as cp
on c.id_category = cp.id_category and c.id_user = cp.id_user
left join transaction t
on t.id_counterpart = cp.id_counterpart and t.id_user = cp.id_user and year(t.date) = 2019 and month(t.date) = 7 and t.id_user = 1
group by c.id_category, c.category
See the demo.
Results:
| category | total |
| -------- | ------ |
| cat_a | 372.05 |
| cat_b | -16.04 |
| cat_c | 0 |

Loop through each ID with more than 3 records in the same table

This is my table:
placeID | name | time
My goal is to remove the oldest records if the placeID has more than 3 record in the table.
It's pretty hard to understand, so example will make it clear:
1 | "Some Name" | *fresher timestamp*
1 | "Some Name" | *fresher timestamp*
1 | "Some Name" | *older timestamp* -- > Delete this result since there are more than 3 records, and this is the older than the rest
1 | "Some Name" | *older timestamp* -- > Delete this result since there are more than 3 records, and this is older than the rest
1 | "Some Name" | *fresher timestamp*
2 | "Some Name" | *fresher timestamp*
2 | "Some Name" | *fresher timestamp*
My trouble: How do I loop for each placeID that has more than 3 record in my table?
Removing the oldest results will not be a problem.
What I tried:
SELECT placeID,COUNT(placeID) FROM place_fbStatus WHERE count(placeID) > 3
Error: #1111 - Invalid use of group function
Another Try:
SELECT id, placeID
FROM place_fbStatus
HAVING COUNT( placeID ) >4
LIMIT 0 , 30
Problem: Show only one placeID
Here my Answer:
First thing is to create a PRIMARY KEY on your Table. So it is easy to DELETE a ROW with this.
Create the Table:
CREATE TABLE `mytable` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`placeID` INT(11) DEFAULT NULL,
`name` VARCHAR(32) DEFAULT NULL,
`time` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `placeID` (`placeID`,`time`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
Insert some stuff:
INSERT INTO `mytable` (`id`, `placeID`, `name`, `time`)
VALUES
(1, 1, 'Some Name', '2015-01-01 00:00:00'),
(2, 1, 'Some Name', '2015-01-02 00:00:00'),
(3, 1, 'Some Name', '2015-01-10 00:00:00'),
(4, 1, 'Some Name', '2015-01-09 00:00:00'),
(5, 2, 'Some Name', '2015-02-01 00:00:00'),
(6, 2, 'Some Name', '2015-01-30 00:00:00'),
(7, 1, 'Some Name', '2015-01-08 00:00:00');
i add rid ( ROW ID per Place ) and the Rows are in the right order
SELECT #rid:=IF( #pid = m.placeID, #rid+1 , 1) rid, m.*, #pid:=m.placeID AS pid
FROM mytable m, (SELECT #rid:=0, #pid:=-1) AS tmp
ORDER BY placeID,TIME ASC
And at last the Query to DELETE the ROWs:
DELETE mt FROM mytable mt
INNER JOIN (
SELECT * FROM (
SELECT #rid:=IF( #pid = m.placeID, #rid+1 , 1) rid, m.*, #pid:=m.placeID AS pid
FROM mytable m, (SELECT #rid:=0, #pid:=-1) AS tmp
ORDER BY placeID,TIME ASC
) AS x
WHERE x.rid >3
) AS dt ON mt.id = dt.id ;
You almost nailed it. What you need is to combine GROUP BY and HAVING
SELECT placeID, count(placeID) AS cnt
FROM place_fbStatus
GROUP BY placeID HAVING cnt>3
DELETE FROM Table WHERE ID NOT IN (SELECT TOP 3 ID FROM Table)
Refer to this thread
Although, it seems after trying it myself, it seems some versions of mysql dont yet support limit clauses in subqueries (This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'). To workaround this, try using an alternate subquery that doesnt involve limits.

Multiple queries into one (Report)?

How do I combine multiple queries into one?
For example:
//Successful Sales:
SELECT username, count(*) as TotalSales, sum(point) as Points FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 1 group by username
/Return Sales:
SELECT username, count(*) as Return FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 2 group by username
//Unsuccessful Sales:
SELECT username, count(*) as UnsuccessfulSales FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND (status = 3 OR status = 6) group by username
So the report look something like this:
Also How do I add percentage of return?
Note: Fixed SQL queries
I have tried doing this but couldn't get it to work?
SELECT username, TotalSales, Points, Return
FROM (
SELECT username, count(*) as TotalSales, sum(point) as Points FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 1 group by username
UNION
SELECT count(*) as Return FROM sales where submit_date >= 1301612400 AND submit_date <= 1304204400 AND status = 4 group by username
)
..
// Example Data Structure
CREATE TABLE IF NOT EXISTS `sales2` (
`salesid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`point` int(11) NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`salesid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `sales2` (`salesid`, `username`, `point`, `status`) VALUES
(1, 'User1', 2, 1),
(2, 'User1', 2, 1),
(3, 'User2', 11, 1),
(4, 'User2', 1, 2),
(5, 'User3', 5, 6);
field status = 1, successful Sales and show point
status 2 - return sales
status 3/6 - unsuccessful sales:
UPDATE:
For your first question, I think this will do what you want (but be warned, this query is dog slow, full of table scans... You should ask for a more experienced stack overflow user to optimize that for you):
SELECT
distinct(outer_sales.username),
(SELECT count(*) as Points FROM sales where status = 1 AND username = outer_sales.username) as TotalSales,
(SELECT sum(point) as Points FROM sales where status = 1 AND username = outer_sales.username) as Points,
(SELECT count(*) FROM sales where status = 2 AND username = outer_sales.username) as Return,
(SELECT count(*) FROM sales where (status = 3 OR status = 6) AND username = outer_sales.username) as UnsuccessfulSales
FROM
sales outer_sales
ORDER BY
outer_sales.username;
And for the second question, if you just want to add a percent sign to the Return column, you can USE the CONCAT function: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat.
Try:
SELECT CONCAT(CAST(COUNT(*) AS CHAR), '%') AS Return ...
If the number (and types) of columns match in the queries, you can use UNION to combine the results of the 3 queries.