gpt4 book ai didi

MYSQL查询获取日期差

转载 作者:行者123 更新时间:2023-11-29 14:30:18 27 4
gpt4 key购买 nike

我有一个带有以下列和数据的表事务

id  transaction_date trans_type account_id agents_id transaction_date price miles
1 2012-02-08 Buy 1 1 2010-02-08 0.016 12000
2 2012-03-01 Sell 2 2 2012-03-10 0.256 -2000
3 2012-03-27 Buy 3 3 2012-03-27 0.256 10000
4 2012-03-28 Sell 4 4 2012-03-28 0.589 -11000
5 2012-03-29 Buy 5 5 2012-03-29 0.87 25000
6 2012-03-29 Sell 6 6 2012-02-29 0.879 -12000
7 2012-04-01 Sell 7 7 2012-04-01 0.058 -15000

Account Table
id Program_id
1 1
2 1
3 2

Program table
id Abbreviation
1 AA
2 AC

Agents table
id Name
1 Bob
2 Ben

我想获取首次销售日期和首次购买日期,以获得交易出售前的平均天数,以获得交易在库存中的天数,所以应该是

  (Sell date)2012-03-01 - (Buy date)2012-02-08

我正在尝试这个

SELECT 
case when t.trans_type ='Sell' then transaction_date end as SellDate
,case when t.trans_type ='Buy' then transaction_date end as BuyDate
,DATEDIFF(case when t.trans_type ='Sell' then transaction_date end
,case when t.trans_type ='Buy' then transaction_date end) as Date
,transaction_date
FROM transactions t
order by transaction_date

但日期总是为 NULL

这是完整的查询

SELECT p.abbreviation,ag.name
,sum(-1.00 * t.miles * t.price - coalesce(t.fees,0) - coalesce(c.cost,0)) as profit
,sum(t.miles) 'Totakl Miles'
,avg(price / miles) 'Average'
,transaction_date
FROM transactions t
inner join accounts a on t.account_id = a.id
inner join programs p on a.program_id = p.id
inner join agents ag on t.agent_id = ag.id
LEFT JOIN (
SELECT rp.sell_id, sum(rp.miles * t.price) as cost
from report_profit rp
inner join transactions t on rp.buy_id = t.id
where t.miles > 50000
group by rp.sell_id
order by rp.sell_id
) c on t.id = c.sell_id
where t.transaction_date BETWEEN '2012-03-14' AND '2012-04-14'
Group by p.id , ag.id

编辑

我尝试了liquvicar答案,但由于我添加了分组,所以出现错误“子查询返回多个记录”

有人可以指导我吗?

提前致谢...

最佳答案

尝试这样的子查询

SELECT 
DATEDIFF(
(
SELECT MIN(date)
FROM Transaction
WHERE trans_type='Sell'
) AS first_sell_date
,
(
SELECT MIN(date)
FROM Transaction
WHERE trans_type='Buy'
) AS first_buy_date
)

编辑:遵循OP评论并使用完整查询更新问题。

你不能只将 DATEDIFF 包裹在 MIN 调用中吗?

DATEDIFF(
MIN(case when t.trans_type ='Sell' then transaction_date end),
MIN(case when t.trans_type ='Buy' then transaction_date end)
) as Date

关于MYSQL查询获取日期差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10140227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com