1
Name      Price  qty
Deen      $11    150
Ann       $12    100
Anthony   $13    250
Anthony   $13    250
Anthony   $14    150

SELECT name, SUM(qty), MIN(price) FROM table GROUP BY name

我需要按名称分组,数量总和,仅以最低价格为例

例子

   Name      Price   qty
    Deen      $11    150
    Ann       $12    100
    Anthony   $13    500

任何人都可以帮助我使用 sql 吗?

4

3 回答 3

2

所以这将是:

SELECT
  t.Name,
  MinPrices.MinPrice,
  SUM(t.qty) AS SumQty
FROM
  (SELECT MIN(Price) AS MinPrice, Name FROM t GROUP BY Name) AS MinPrices
  LEFT JOIN
    t ON MinPrices.Name=t.Name
    AND
    MinPrices.MinPrice=t.Price
GROUP BY
  t.Name

-看这个小提琴

于 2013-11-03T13:25:45.830 回答
1
SELECT
    name,
    MIN(price),
    SUM(qty)
FROM
    table
GROUP BY
    name
ORDER BY
    2

再次查看您的查询。我按照您的建议制作了一张表格,并进行了查询,它几乎返回了您想要的结果,除了 Anthony 的 sum = 650。

于 2013-11-03T13:30:16.130 回答
1
SELECT
    t1.name,
    SUM(t1.qty),
    t1.price
FROM table t1
WHERE
    t1.price = (SELECT MIN(t2.price) FROM table t2 WHERE t1.name = t2.name)
GROUP BY t1.name
ORDER BY t1.price
于 2013-11-03T13:34:21.073 回答