-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

ここでフィドルを参照してください。

編集:少なくとも1つの変更があるたびにすべてのアイテムを表示する必要がある場合は、これを使用できます:

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

a を使用しLEFT 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 に答える
0

私は次のようなことを信じています:

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

動作する可能性があります

于 2013-08-26T19:59:08.340 に答える