我有下表:
+-------------+--------------+
| product | purchased |
+-------------+--------------+
| Hammer | <timestamp> |
| Nipper | <timestamp> |
| Saw | <timestamp> |
| Nipper | <timestamp> |
| Hammer | <timestamp> |
| Hammer | <timestamp> |
| Saw | <timestamp> |
| Saw | <timestamp> |
| Saw | <timestamp> |
+-------------+--------------+
我想查看有关这些产品的保修状态的摘要。保修期为自购买之日起 5 年。因此,使用今天的日期应该可以检查产品是否在保修期内(基于购买日期)。我也想现在最后一次购买的产品何时超出保修期。这是一个示例表:
+-------------+--------------+----------------+------------------+------------------+
| product | count | warranty valid | warranty expired | last p. warranty |
+-------------+--------------+----------------+------------------+------------------+
| Hammer | 3 | 1 | 2 | 10.03.2015 |
| Nipper | 2 | 2 | - | 01.01.2014 |
| Saw | 4 | 1 | 3 | 02.12.2013 |
+-------------+--------------+----------------+------------------+------------------+
我尝试为此示例创建查询,但我不知道如何循环每个产品的结果以计算有效保修等。这就是我目前所拥有的:
SELECT
product,
date_format(from_unixtime(purchased), '%d.%m.%Y') AS purchaseDate,
date_format(date_add(from_unixtime(purchased), INTERVAL 5 YEAR), '%d.%m.%Y') AS warrantyEnd,
(
SELECT
COUNT(product)
FROM
productWarranty
) AS count
FROM
productWarranty s
GROUP BY
product
我不知道如何编写子查询,因为我需要使用 WHERE product = Hammer 之类的东西。但是我怎样才能告诉 sql 为每个产品循环呢?