我有以下查询。 我需要在我的组中仅选择最旧的行(按DATE列)。保持我的条件(在哪里和分组)。
SELECT
table.*
from table
where views > $views AND sales>23
group by
name
更清楚一点就像传递frm这第一张桌子
+--------------------+-----------+--------------------+-----------+
| name | views | DATE | sales |
+--------------------+-----------+--------------------+-----------+
| sue1 | 494 | 2014-06-23 12:08:29| 26 |
| sue2 | 494 | 2014-06-25 12:08:29| 34 |
| sue3 | 494 | 2014-06-27 12:08:29| 45 |
| sue4 | 520 | 2014-06-26 12:08:29| 56 |
| sue5 | 570 | 2014-06-24 12:08:29| 20 |
| sue5 | 570 | 2014-06-24 12:08:29| 28 |
+--------------------+-----------+--------------------+-----------+
到第二个
+--------------------+-----------+--------------------+-----------+
| name | views | DATE | sales |
+--------------------+-----------+--------------------+-----------+
| sue3 | 494 | 2014-06-27 12:08:29| 45 |
| sue4 | 520 | 2014-06-26 12:08:29| 56 |
| sue5 | 570 | 2014-06-24 12:08:29| 28 |
+--------------------+-----------+--------------------+-----------+
marko.c
我尝试过做
的子选择SELECT
table.*
from table
where views > $views AND sales>23
and date in (select max(date) from table where views > $views AND sales>23)
group by
name
但它没有用。任何人
答案 0 :(得分:0)
作为第一关,老实说,我不确定你想要什么。我认为您的要求是按照最早的日期获取所有独特的观看次数...但无论如何,如果您想要每件事物的最早日期,那么只需在订购后再进行分组。
SELECT * FROM(
SELECT
table.*
FROM table
WHERE views > $views AND sales>23
ORDER BY date
) AS t
GROUP BY name;
当您在某个日期进行聚合时,请将其反向思考..
MAX(date) will give you the NEWEST date because it is the greatest date.
MIN(date) will give you the OLDEST date because it is the oldest / smallest date.
所以如果你想做其他发布的查询,你可以做
SELECT
table.*
from table
where views > $views AND sales>23
and date in (select MIN(date) from table where views > $views AND sales>23)
group by
name
并查看MIN(日期)是否可以解决问题
答案 1 :(得分:0)
您正在选择子查询中的最大总日期,但实际需要的是每个名称的最小(最早)日期。
SELECT
t1.*
from table t1
join (
select
t2.name,
min(t2.date) min_date
from table t2
where t2.views > $views AND t2.sales > 23
group by t2.name
) t2 on t2.name = t1.name and t2.min_date = t1.date
where t1.views > $views AND t1.sales > 23