假设我有一个名为'库存'的表格,每天我都会列出每个项目及其数量。
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
关于如何做到这一点的任何想法?
答案 0 :(得分: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
请参阅小提琴here。
编辑:如果您需要在至少有一次更改时显示所有项目,可以使用此功能:
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)
小提琴是here。
答案 1 :(得分:0)
我相信:
Select day, (Select Item, Quantity From tables Where Criteria) From tables Where Criteria Group By Day.
可以工作
答案 2 :(得分: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 )
测试它并且它起作用,至少在我理解这个问题的时候。
答案 3 :(得分:0)
您可以使用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