我是mysql的新手,需要帮助。我有一个表如下,我正在尝试运行类似于下面显示的SQL查询。我在以下面的格式定义年份时遇到了问题。
我的预期查询是找到销售>的商品代码。 20,利润> 20,和tsv>所有5年的10年。如果即使一年没有比较值,也不应列出。
select Item from inventory
WHERE Sales > 20 AND Profit> 20 and TSV > 10
AND YEAR ( 2010 AND 2011 AND 2013 AND 2009 AND 2012)
+----------+-----------+--------+----------+-----------+--------+
| Item | YEAR | Sales | Profit | TSV | REC |
+----------+-----------+--------+----------+-----------+--------+
| machine | 2011 | 10| 10 | 20 | 10 |
| machine | 2010 | 8 | 15 | 6 | 2 |
| machine | 2013 | 15| 5 | 11 | 5 |
| machine | 2009 | 3 | 8 | 9 | 13 |
| machine | 2012 | 6 | 12 | 18 | 16 |
| decors | 2010 | 11| 10 | 13 | 22 |
| decors | 2011 | 9 | 9 | 16 | 12 |
| decors | 2012 | 3 | 7 | 11 | 9 |
| decors | 2013 | 13| 23 | 9 | 10 |
| decors | 2009 | 4 | 9 | 10 | 8 |
| sp parts | 2009 | 22| 25 | 17 | 22 |
| sp parts | 2010 | 21| 22 | 11 | 14 |
| sp parts | 2011 | 28| 30 | 29 | 23 |
| sp parts | 2012 | 23| 28 | 12 | 8 |
| sp parts | 2013 | 21| 24 | 24 | 32 |
-----------------------------------------------------------------
答案 0 :(得分:1)
这应该可以解决问题,方法是使用group by来检查每个不同的年份
SELECT Item FROM
inventory
WHERE Sales > 20 AND Profit> 20 AND TSV > 10
AND `YEAR` IN( 2010,2011,2013,2009,2012)
GROUP BY Item
HAVING COUNT(DISTINCT `YEAR`) =5
Demo