这是原始的MySQL声明:
select transactions.username,
count(transactions.username) as total_transactions,
last_device,
last_transaction
from transactions
inner join (select username,
terminal as last_device,
request_date as last_transaction
from transactions t1
where request_date =
(select max(request_date)
from transactions t2
where t1.username = t2.username)) as transactions_per_user
on transactions_per_user.username = transactions.username
group by username;
甲骨文并不喜欢这句话,所以在经过大量的反复试验之后我将其改写为:
select transactions_per_user.username,
count(transactions_per_user.username) as total_transactions,
MAX(transactions_per_user.last_transaction) as last_transaction,
MAX(transactions_per_user.last_device) as last_device
from
transactions
inner join
(
select username, terminal as last_device, request_date as last_transaction
from transactions t1
where request_date = (select max(request_date)
from transactions t2 where t1.username=t2.username)
)
transactions_per_user on transactions_per_user.username=transactions.username
group by transactions_per_user.username;
这似乎是对的,但我担心在那里使用MAX。我不太明白为什么会这样。任何人都可以验证它是否可以,如果不帮助我编写一个可以在oracle中保持接近mysql的语句,如果sql将在oracle和mysql中运行,那就更好了。
基本上我正在尝试生成一个按用户分组的表,列出了他们上次的交易日期以及最后使用的设备以及他们所做的交易次数。
答案 0 :(得分:1)
我使用PL / SQL美化器来格式化相同格式的语句,并使用TortuiseSVN来比较它们。
第一次查询:
SELECT transactions.username,
COUNT(transactions.username) AS total_transactions,
last_device,
last_transaction
FROM transactions
INNER JOIN (SELECT username,
terminal AS last_device,
request_date AS last_transaction
FROM transactions t1
WHERE request_date =
(SELECT MAX(request_date)
FROM transactions t2
WHERE t1.username = t2.username)) AS transactions_per_user
ON transactions_per_user.username = transactions.username
GROUP BY username
第二个查询:
SELECT transactions_per_user.username,
COUNT(transactions_per_user.username) AS total_transactions,
MAX(transactions_per_user.last_transaction) AS last_transaction,
MAX(transactions_per_user.last_device) AS last_device
FROM transactions
INNER JOIN (SELECT username,
terminal AS last_device,
request_date AS last_transaction
FROM transactions t1
WHERE request_date =
(SELECT MAX(request_date)
FROM transactions t2
WHERE t1.username = t2.username)) transactions_per_user
ON transactions_per_user.username = transactions.username
GROUP BY transactions_per_user.username;
以下是更改: