好吧我有一张表,我需要从GROUP BY函数中获取相关日期......
Here is a sample of the data:
min_price, day
140000 2010-09-26
130000 2010-09-27
154991 2010-10-08
143000 2010-10-09
156470 2010-10-10
I would like this result:
130000 2010-09-27
143000 2010-10-09
Here is the SQL I use:
SELECT MIN(min_price) AS low_price, min_price, day
FROM compress
WHERE item_name = '$item'
GROUP BY EXTRACT(MONTH FROM day), EXTRACT(YEAR FROM day)
Here is what I get:
130000 2010-09-26
143000 2010-10-08
如您所见,日期与最小行值不匹配。我需要他们匹配。我可以用什么SQL来获得结果?
答案 0 :(得分:2)
Select C.min_price, C.day
From compress As C
Where C.item_name = '$item'
And Exists (
Select 1
From compress As C2
Where C2.item_name = C.item_name
And Extract(Month From C2.day) = Extract(Month From C.day)
And Extract(Year From C2.day) = Extract(Year From C.day)
Group By Extract(Month From C2.day), Extract(Year From C2.day)
Having C.min_price = Min(C2.min_price)
)
<强> ADDITION 强>
MySQL更适合加入,所以这里是同一查询的变体
Select C.min_price, C.day
From compress As C
Join (
Select C2.item_name
, Extract(Month From C2.day) As ItemMonth
, Extract(Year From C2.day) As ItemYear
, Min(C2.min_price) As MinPrice
From compress As C2
Group By C2.item_num, Extract(Month From C2.day), Extract(Year From C2.day)
) As Z
On Z.item_name = C.item_name
And Z.ItemMonth = Extract(Month From C.day)
And Z.ItemYear = Extract(Year From C.day)
And Z.MinPrice = C.min_price
Where C.item_name = '$item'
真正放慢任何变化的是每行调用Extract。如果您的日历表包含每个日期的行以及日期的月份和年份的列,并且您的日历表涵盖了数据中的日期范围,那么您可以执行以下操作:
Select C.min_price, C.day
From compress As C
Join Calendar As Cal
On Cal.Date = C.Day
Join (
Select C3.item_name
, Cal3.Month, Cal3.Year
, Min(C3.min_price) As MinPrice
From compress As C3
Join Calendar As Cal3
On Cal3.Date = C3.day
Group By C3.item_num, Cal3.Month, Cal3.Year
) As Z
On Z.item_name = C.Item_name
An Z.Month = Cal.Month
And Z.Year = Cal.Year
And Z.MinPrice = C.min_price
Where C.item_name = '$item'
答案 1 :(得分:0)
SELECT min_price AS low_price, min_price, day
FROM compress
WHERE item_name = '$item' AND min_price = MIN(min_price)
GROUP BY EXTRACT(MONTH FROM day), EXTRACT(YEAR FROM day)
然后,这将选择min_price与MIN(min_price)
相同的行答案 2 :(得分:0)
您的SQL无效。在分组时,显示列表中的每一列(不是表达式的组的一部分)必须通过聚合函数传递,例如, AVG(),MIN(),MAX(),但你只是要求“白天”。
请用自然语言(英语)说明您想要达到的目标。你的例子不是很清楚。
答案 3 :(得分:0)
如果我已正确理解问题,这应该有效......
mysql> select * from stack;
+-----------+------------+
| min_price | myday |
+-----------+------------+
| 140000 | 2010-09-26 |
| 130000 | 2010-09-27 |
| 154991 | 2010-10-08 |
| 143000 | 2010-10-09 |
| 156470 | 2010-10-10 |
+-----------+------------+
5 rows in set (0.00 sec)
mysql> select a.* from stack as a inner join
-> (select min(min_price) as my_price from stack group by extract(YEAR_MONTH from myday)) as b
-> on a.min_price = b.my_price;
+-----------+------------+
| min_price | myday |
+-----------+------------+
| 130000 | 2010-09-27 |
| 143000 | 2010-10-09 |
+-----------+------------+
2 rows in set (0.00 sec)
您需要加入主键才能避免意外结果。如果查询速度很慢,请为subselect创建一个临时表,在其上构建索引,然后使用该表与主表联接。