gpt4 book ai didi

sql - T-sql每天获取最小值和最大值

转载 作者:行者123 更新时间:2023-12-04 20:54:06 25 4
gpt4 key购买 nike

我正在尝试编写一个查询,每天从价格明细表中获取每件商品的最低和最高价格。

在价格明细表中,价格一天设置多次,因此同一日期有很多记录。所以我想要一个表,其中每个日期都有一行,然后将该表连接到同一个表,因此对于每个不同的日期,我想要最小值和最大值。

USE [a_trading_system]
GO

/****** Object: Table [dbo].[price_details] Script Date: 07/01/2012 17:28:31 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[price_details](
[price_id] [int] IDENTITY(1,1) NOT NULL,
[exch_ticker] [varchar](8) NOT NULL,
[price_set_date] [datetime] NOT NULL,
[buy_price] [decimal](7, 2) NOT NULL,
[sell_price] [decimal](7, 2) NOT NULL,
CONSTRAINT [PK_price_detail] PRIMARY KEY CLUSTERED
(
[price_id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [dbo].[price_details] WITH CHECK ADD CONSTRAINT [FK_price_details_Contract] FOREIGN KEY([exch_ticker])
REFERENCES [dbo].[Contract] ([exch_ticker])
GO

ALTER TABLE [dbo].[price_details] CHECK CONSTRAINT [FK_price_details_Contract]
GO

SQL 查询

select distinct 
substring(convert(varchar(12),p1.price_set_date), 0, 12),
p2.exch_ticker,
(select MIN(buy_price) from price_details ),
(select MAX(buy_price) from price_details )
from price_details as p1

left join price_details as p2 on p2.exch_ticker = p1.exch_ticker

where p1.exch_ticker = p2.exch_ticker

group by p1.price_set_date, p2.exch_ticker

总结

表中有许多价格是在同一天设定的。想要每个交易所代码每天的最小值和最大值。

谢谢

最佳答案

一个简单的 group by 应该可以工作:

select  cast(price_set_date as date) as [Date]
, exch_ticker
, min(buy_price) as MinPrice
, max(buy_price) as MaxPrice
from price_details as p
group by
exch_ticker
, cast(price_set_date as date)

不确定您的示例查询为何使用自联接。如果有充分的理由,请为您的问题添加解释。

关于sql - T-sql每天获取最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11283749/

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