T-sql每天获取最小值和最大值 [英] T-sql get min and max value for each day

查看:323
本文介绍了T-sql每天获取最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a query where for each day I get the minimum and maximum price for each item from price details table.

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

In price details table prices are set multiple times a day so there are many records for the same date. So I want a table where there is one row for each date and then join that table to the same table so for each distinct date I want the minimum and maximum value.

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

摘要

表在同一天设定了许多价格.想要每个交易所报价的每天的最小值和最大值.

Table has many prices set on the same day. Want min and max values for each day for each exch ticker.

谢谢

推荐答案

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

A simple group by should work:

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)

不确定为什么您的示例查询使用自连接.如果有充分的理由,请在您的问题中添加解释.

Not sure why your example query is using a self join. If there's a good reason please add an explanation to your question.

这篇关于T-sql每天获取最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆