如果在同一天,7天或14天的间隔内以相同/不同供应商的不同价格采购材料,如何使用SQL代码提取数据? 我累了但不能为此做代码。我是SQL新手。
数据表 - 项目日期供应商物料数量NetPrice
答案 0 :(得分:0)
MariaDB [sandbox]> DROP TABLE IF EXISTS T;
Query OK, 0 rows affected (0.11 sec)
MariaDB [sandbox]> CREATE TABLE T( Item INT ,Dt DATE ,Vendor INT, PRICE INT);
Query OK, 0 rows affected (0.16 sec)
MariaDB [sandbox]>
MariaDB [sandbox]> INSERT INTO T VALUES
-> (1,'2017-06-12',1,10),(1,'2017-06-25',1,20),
-> (1,'2017-06-26',1,30),(1,'2017-06-26',1,40),
-> (2,'2017-06-26',1,10),(2,'2017-06-26',1,40),
-> (3,'2017-05-26',1,10),(3,'2017-05-26',1,40),
-> (4,'2017-06-20',1,10),(4,'2017-06-20',1,40),
-> (5,'2017-06-12',1,10),(5,'2017-06-12',1,40);
Query OK, 12 rows affected (0.07 sec)
Records: 12 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]> select s.item,
-> max(case when src = 1 then s.prices else 0 end) as PricesToday,
-> max(case when src = 2 then s.prices else 0 end) as Prices7,
-> max(case when src = 3 then s.prices else 0 end) as Prices14
-> from
-> (
-> SELECT 1 as src,item,COUNT(DISTINCT PRICE) Prices
-> FROM T
-> where dt = date(now())
-> GROUP BY ITEM HAVING COUNT(DISTINCT PRICE) > 1
-> union
-> SELECT 2,item,COUNT(DISTINCT PRICE) Prices
-> FROM T
-> where datediff(date(now()),dt) <= 7
-> GROUP BY ITEM HAVING COUNT(DISTINCT PRICE) > 1
-> union
-> SELECT 3,item,COUNT(DISTINCT PRICE) Prices
-> FROM T
-> where datediff(date(now()),dt) <= 14
-> GROUP BY ITEM HAVING COUNT(DISTINCT PRICE) > 1
-> ) s
-> group by s.item;
+------+-------------+---------+----------+
| item | PricesToday | Prices7 | Prices14 |
+------+-------------+---------+----------+
| 1 | 2 | 3 | 4 |
| 2 | 2 | 2 | 2 |
| 4 | 0 | 2 | 2 |
| 5 | 0 | 0 | 2 |
+------+-------------+---------+----------+
答案 1 :(得分:0)
这样的事情。
DELIMITER $$
在your_good_old_table更新后创建TRIGGER check_price
对于每一行
开始
如果NEW.price&lt;&gt; OLD.price那么
INSERT INTO your_new_better_table(newprice)
VALUES(NEW.newprice);
万一;
结束;
$$
DELIMITER;
注意:编辑可以格式化代码吗?我不能用ctrl + k
来得到它答案 2 :(得分:0)
以下查询检索所有记录,对于具有其他价格的相同物料,在14天内存在另一记录。更改14到7或0或您要检查的任何其他值。
select *
from mytable
where exists
(
select *
from mytable other
where other.material = mytable.material
and other.netprice <> mytable.netprice
and abs(datediff(other.date, mytable.date)) <= 14 -- or 7 or 0
)
order by material, date, netprice;