Reputation: 835
id | user_id | prd_id | amnt | dis
1 | 1 | 10 | 200 | 23
2 | 2 | 10 | 300 | 11
3 | 3 | 20 | 100 | 26
4 | 2 | 20 | 50 | 12
5 | 4 | 30 | 100 | 22
6 | 2 | 40 | 600 | 18
7 | 2 | 30 | 100 | 16
I want 2 result from above table :
First by prod_id
as below
prd_id | user_id | cont | highestamt | disc
10 | 2 | 2 | 300 | 11
20 | 3 | 2 | 100 | 26
30 | 4 | 2 | 100 | 22
40 | 2 | 1 | 600 | 18
Second by user_id
as below:
user_id | cont | bid on prd_id | winner on bid prod_id |
1 | 1 | 10 | - | -
2 | 4 | 10,20,30,40 | 10,40 |
3 | 1 | 20 | 20 |
4 | 1 | 30 | 30 |
UPDATE : ex: above : user_id = 2 has bid on product 10,20,30,40 ( bid on prd_id ) hence his bidding cont = 4 ...and out of which he is winner in 10,40 ( winner on bid prod_id ) ..WHY ONLY 10,40 and not 30 ...bcz user_id =4 has bid on prd=30 with amt =100 and user_id =2 with amt=100 ..but first bid was made by user=4 on prd=30 hence he is winner for prd=30 ( for same amt )
Tried below query for by prd_id
but it giving me some wrong result.
SELECT `prd_id`, `user_id` , count('prd_id') as cont , max(`amnt`) as highestamt,disc
FROM `proddtails`
group by `prd_id` order by `prd_id`
above query result as below : ( user_id,disc
not coming proper )
prd_id | user_id | cont | highestamt | disc
10 | 2 | 2 | 300 | 11
20 | 2 | 2 | 100 | 11
30 | 2 | 1 | 100 | 11
40 | 2 | 1 | 600 | 11
For second by user_id
I am not getting what will be query.
Thanks
UPDATE :
THANKS FOR HARSHIL : http://www.sqlfiddle.com/#!9/5325a6/5/1
but after some more entry i found this bug : http://www.sqlfiddle.com/#!9/e04063/1 for second : for user_id but works well for prd_id (first query )
user_id cont bid_on_prd_id winner_on_bid_prod_id
1 1 10 (null)
2 4 10,20,40,30 10,40,30
3 1 20 20
4 1 30 30
but i want as below :
without null user_id
user_id cont bid_on_prd_id winner_on_bid_prod_id
2 4 10,20,30,40 10,40
3 1 20 20
4 1 30 30
with null user_id ( but in my wamp server i don't see null in winner_on_bid_prd_id for user_id =1 , i get value 10 instead of null )
user_id cont bid_on_prd_id winner_on_bid_prod_id
1 1 10 (null)
2 4 10,20,30,40 10,40
3 1 20 20
4 1 30 30
Upvotes: 3
Views: 105
Reputation: 3592
For prd_id:
select t1.prd_id,t1.user_id,
(select count(*) from tablename where prd_id = t1.prd_id)as cont,
t1.amnt as highststatment,
t1.dis as disc
from tablename t1
where (t1.prd_id,t1.amnt) in
(select prd_id, max(amnt) from tablename group by prd_id)
group by t1.prd_id;
For usr_id:
select t1.user_id,
count(*) as cont,
Group_concat(t1.prd_id separator ',') as bid_on_prd_id,
(select Group_concat(distinct t2.prd_id separator ',')
from tablename t2
where t2.user_id = t1.user_id
and (t2.id) in
(select min(id) from tablename
where (prd_id,amnt) in
(select prd_id,max(amnt) from tablename group by prd_id)
group by prd_id
)
) as winner_on_bid_prod_id
from tablename t1
group by t1.user_id
having winner_on_bid_prod_id IS NOT NULL;
Upvotes: 4