-1

假设我有一张名为“库存”的表格,每天我都会列出每个项目及其数量。

inventory
---------------------
day | item | quantity
1    Apples   5
1    Oranges  3
2    Apples   5
2    Oranges  3
3    Apples   5
3    Oranges  3
3    Peaches  8
4    Apples   5
4    Oranges  3
4    Peaches  8
5    Apples   2
5    Oranges  3
5    Peaches  8

通过重复数据删除,我想摆脱与前一天具有完全相同数据的任何一天。所以结果表应该是这样的:

inventory
---------------------
day | item | quantity
1    Apples   5
1    Oranges  3
3    Apples   5
3    Oranges  3
3    Peaches  8
5    Apples   2
5    Oranges  3
5    Peaches  8

关于如何做到这一点的任何想法?

4

4 回答 4

1

如果你想考虑一些缺失的日子,你可以使用这样的查询:

SELECT
  i.day, i.item, i.quantity
FROM (
  SELECT t1.day, t1.item, t1.quantity, MAX(t2.day) as prec_day
  FROM
    inventory t1 LEFT JOIN inventory t2
    ON t1.item=t2.item AND t1.day>t2.day
  GROUP BY
    t1.day, t1.item, t1.quantity) i
  LEFT JOIN inventory i2
  ON i.item=i2.item AND i.prec_day=i2.day
WHERE
  i2.day IS NULL or i.quantity<>i2.quantity

在此处查看小提琴。

编辑:如果您需要在至少有一个更改时显示所有项目,您可以使用这个:

SELECT
  inventory.*
FROM
  inventory
WHERE
  day IN (
    SELECT
      i.day
    FROM (
      SELECT t1.day, t1.item, t1.quantity, MAX(t2.day) as prec_day
      FROM
        inventory t1 LEFT JOIN inventory t2
        ON t1.item=t2.item AND t1.day>t2.day
      GROUP BY
        t1.day, t1.item, t1.quantity) i
      LEFT JOIN inventory i2
      ON i.item=i2.item AND i.prec_day=i2.day
    WHERE
      i2.day IS NULL or i.quantity<>i2.quantity)

小提琴在这里

于 2013-08-26T20:13:42.390 回答
0

我相信类似的东西:

Select day, (Select Item, Quantity From tables Where Criteria) From tables Where Criteria Group By Day.

可以工作

于 2013-08-26T19:59:08.340 回答
0

以下解决方案使用协调的子选择。

select day, item, quantity
from yourTable t
where quantity <> ( select quantity from yourTable y where y.day = t.day - 1 and y.item = t.item )

测试它并且它有效,至少我理解这个问题。

于 2013-08-26T20:00:34.550 回答
0

您可以使用 aLEFT JOIN查找与前一天相同的库存项目,并将它们排除在WHERE子句中。这是一个SQLFiddle

SELECT
   inv.day
  ,inv.item
  ,inv.quantity
FROM inventory AS inv
LEFT JOIN inventory AS prev_day
  ON prev_day.day = inv.day - 1
  AND prev_day.item = inv.item
  AND prev_day.quantity = inv.quantity
WHERE prev_day.day IS NULL
于 2013-08-26T20:04:55.637 回答