Gday All,
我试图在一段时间内获得给定客户的首次交易的详细信息。
请考虑以下事项:
SELECT MIN(t.transaction_date_start), t.*
FROM transactions t
WHERE t.customer_id IN (1,2,3)
AND t.transaction_date_finished >= '2010-02-01 00:00:00'
AND t.transaction_date_finished <= '2010-02-28 23:59:59'
GROUP BY t.customer_id
上面的SQL正确输出了最小的事务日期,但其余的数据并不是我所期望的。
使用第一个分组客户ID的数据填充,而不是最小值。
为什么MySQL会从两个不同的查询中有效地输出数据?
如何修复SQL以便选择第一个事务的所有详细信息?
干杯,
迈克尔
答案 0 :(得分:1)
我试图在一段时间内获得给定客户的首次交易的详细信息。
你走了:
SELECT TOP 1 *
FROM transactions t
WHERE t.customer_id = 1
AND t.transaction_date_finished >= '2010-02-01 00:00:00'
AND t.transaction_date_finished <= '2010-02-28 23:59:59'
ORDER BY t.transaction_date_start
答案 1 :(得分:1)
欢迎来到GROUP BY“功能”中的MySQL“隐藏列” - 它是documented here。标准SQL不允许您定义GROUP BY
子句,该子句不包含未包含在SELECT子句中的聚合函数(MIN,MAX,COUNT等)中的列:
SELECT MIN(t.transaction_date_start), -- (a) Wrapped in an aggregate function
t.* -- (b) These are not
FROM transactions t
WHERE ...
GROUP BY t.customer_id -- (c) Only customer_id - refer to (b)
要获得与最小日期匹配的行,请使用:
SELECT t.*
FROM TRANSACTIONS t
JOIN (SELECT ta.customer_id,
MIN(ta.transaction_date_start) AS min_date
FROM TRANSACTIONS ta
WHERE ta.transaction_date_finished BETWEEN '2010-02-28 23:59:59' AND '2010-02-01 00:00:00'
GROUP BY ta.customer_id) x ON x.customer_id = t.customer_id
AND x.min_date = t.transaction_date_start
WHERE t.customer_id IN (1, 2, 3)
答案 2 :(得分:0)
可以通过而不是使用group来命令:
select * from transactions where customer_id = 1 and
transaction_date_finished between '2010-02-01 00:00:00' and '2010-02-28 23:59:59'
order by transaction_date_finished limit 1