1

我的表结构如下

vendor_id account_id 价格代码

27 2 0.058 91

29 2 0.065 91

23 2 0.043 91

30 2 0.085 91

31 3 0.085 91

我必须得到代码应该等于 91 的最低价格,给定范围和按 account_id 分组之间的价格

我正在使用选择查询作为

选择 MIN(price) 作为 min_price, account_id, vendor_id from tbl_input_values where code='91' and price>=0 and price<=2 group by account_id

我得到的输出为

min_price account_id vendor_id

0.043 2 27

0.085 3 31

但应该是

min_price account_id vendor_id

0.043 2 23

0.085 3 31

4

4 回答 4

0

试试这个查询 -

SELECT
  t1.*
FROM tbl_input_values t1
JOIN (
  SELECT
    MIN(price) AS min_price,
    account_id
  FROM tbl_input_values
  WHERE code = '91' AND price >= 0 AND price <= 2
  GROUP BY account_id
  ) t2
    ON t1.account_id = t2.account_id AND t1.price = t2.min_price
于 2013-03-13T07:21:27.580 回答
0

尝试;

SELECT tData.price, tData.account_id, tData.vendor_id FROM tbl_input_values, (SELECT price, account_id, vendor_id FROM tbl_input_values ORDER BY price ASC) AS tData WHERE tbl_input_values.account_id = tData.account_id GROUP by tbl_input_values.account_id;
于 2013-03-13T07:42:57.260 回答
0

您的查询正确选择了每个 account_id 的最低价格,但有必要将此价格与 vendor_id 相关联。

这是我的版本:

SELECT iv.price AS min_price, iv.account_id, iv.vendor_id
  FROM tbl_input_values AS iv
  INNER JOIN (select min(price) AS min_price, account_id
    FROM tbl_input_values
    WHERE full_code='91' AND price>=0 AND price<=2
    GROUP BY account_id) AS mp
 ON iv.price=mp.min_price AND iv.account_id=mp.account_id;

如果两个供应商的 account_id 最低价格相同,则此查询将返回两者。

在此处查看 SQL 小提琴http://sqlfiddle.com/#!2/96d24/8

于 2013-03-13T07:33:25.043 回答
0

试试这个查询

 SELECT 
      price, 
      account_id, 
      vendor_id 
 from 
      Table1
 where 
      (vendor_id, price) in 
      (select 
            vendor_id, 
            min(price) 
       from 
            Table1 
       WHERE 
            code = '91' AND 
            price >= 0 AND 
            price <= 2
       group by 
            account_id)

没有使用连接的子查询

  SELECT 
        a.price, 
        a.account_id, 
        a.vendor_id 
  from 
        Table1 a,
        (select 
               vendor_id, 
               min(price) as 'price' 
        from 
               Table1 
        where 
               code='91' and 
               price>=0 and 
               price<=2
        group by 
               account_id) b
  WHERE 
        a.vendor_id = b.vendor_id AND 
        a.price = b.price
于 2013-03-13T07:26:29.787 回答