1

这是我的表结构。

id
veh_id
user_id
amount
...

我还有其他表来关联 user_id 和 veh_id。

我想知道用户在每个 veh_id 上放了多少次金额,以及多少次,这个金额实际上是收到的最高金额。我想为每个可用的用户提供这 2 个计数。

id, veh_id, user_id, amount
1    1       30        100
2    1       32        105
3    2       30        100
4    2       32        95
5    2       33        90

我希望 select 语句给我:

用户 30 出价 2 次,其中 1 次是最高出价者

用户 32 作为出价 2 次和 1 次是最高出价者

用户 33 出价 1 次和 0 次出价最高者

我不知道是否有可能获得这些数字。

4

2 回答 2

0

尝试这个,

select x.user_id, x.bid_times, COALESCE(y.max_times,0) as max_times from
(select user_id, count(*) as bid_times from testt group by user_id) as x
 LEFT JOIN
(select user_id, count(*) as max_times  from testt a where 0=( select count(*) from testt where amount > a.amount and veh_id=a.veh_id ) group by user_id) as y
ON x.user_id=y.user_id
于 2013-07-29T18:50:06.727 回答
0

可能很接近,不确定您如何将车辆关联在一起。

select
  user_id,
  count(*) as num_bids,
  SUM(is_highest) as max_bids
from ( select
  a.user_id,
  COALESCE((select
      MAX(b.amount) < a.amount
    from bid as b
    where b.id < a.id
    and b.veh_id=a.veh_id
  ), 1) as is_highest
from bid as a
) as c
group by user_id

我的理解是用户 30 有 2 个最高出价(车辆的 2 个首次出价)。

编辑:如果您只是在寻找每辆车总共 1 个最高出价,请告诉我。这实际上比回滚查看谁的出价最高要容易得多......

EDIT2:每辆车只有 1 个最大计数的解决方案:

由于某种原因,这似乎应该更简单:

select
 user_id,
 count(*) as num_bids,
 count(vamt) as num_max
from bid
left join (
  select veh_id as vid, max(amount) as vamt
  from bid
  group by veh_id
) as a on vid = veh_id and vamt <= amount
group by user_id
于 2013-07-29T18:14:45.100 回答