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
我想从上表中得到2个结果:
首先by prod_id
如下
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
第二个by user_id
如下:
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 |
更新:例如:上方: user_id = 2已对产品10,20,30,40(对prd_id出价)出价,因此他的出价续= 4 ...而且他的出价是获胜者10,40(竞价prod_id的赢家)..WHY仅10,40而不是30 ... bcz user_id = 4对prd = 30的出价,amt = 100,user_id = 2,amt = 100 ..但是出价是由用户= 4在prd = 30上进行的,因此他是prd = 30的赢家(同样的amt)
尝试by prd_id
的查询,但它给了我一些错误的结果。
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`
以上查询结果如下:( user_id,disc
不合适)
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
对于第二个by user_id
,我无法获得将要查询的内容。
由于
更新:
感谢HARSHIL:http://www.sqlfiddle.com/#!9/5325a6/5/1
但是经过一些更多的输入我发现了这个错误:http://www.sqlfiddle.com/#!9/e04063/1代表第二个:代表user_id 但适用于 prd_id(首次查询)
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
但我想如下:
没有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
使用null user_id (但在我的wamp服务器中,我在win_on_bid_prd_id中看不到user_id = 1的空值,我得到值10而不是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
答案 0 :(得分:4)
对于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;
对于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;