我正在尝试获取**ID_RE**
**Date_Enter,Date_Process,Date_Shipment**
例如,这里有三行。
- **1,2012-02-01,2016-02-01,2015-02-01,Send for MX4343**
- **2,2013-02-01,2008-04-01,2009-02-01,It's For trade**
- **3,2018-02-01,2019-05-01,2007-02-01,Like a environment**
这是最高的:
3,2018-02-01,2019-05-01,2007-02-01,Like a environment
我一直在尝试这个:
SELECT
MAX(Date_Enter),
MAX(Date_Process),
MAX(Date_Shipment),
Description
FROM Reports
但是,不起作用
CREATE TABLE [dbo].[Reports](
[ID_RE] [int] IDENTITY(1,1) NOT NULL,
[Date_Enter] [datetime] NOT NULL,
[Date_Process] [datetime] NOT NULL,
[Date_Shipment] [varchar](20),
[Description] [varchar](20)
CONSTRAINT [PK_Reports] PRIMARY KEY CLUSTERED
(
[ID_RE] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
END
GO
这里我们有一些信息
insert into Reports(Date_Enter,Date_Process,Date_Shipment,Description) values('2012-02-01 02:25:23','2016-02-01 08:45:23','2015-02-01 05:35:23','Send for MX4343')
insert into Reports(Date_Enter,Date_Process,Date_Shipment,Description) values('2013-02-01 01:52:23','2008-04-01 12:45:23','209-02-01 07:35:43','It is For trade')
insert into Reports(Date_Enter,Date_Process,Date_Shipment,Description) values('2018-02-01 04:34:33','2019-05-01 04:35:44','2007-02-01 09:35:09','Like a environment')
答案 0 :(得分:1)
您可以根据自己的要求申请order by
,如下所示。如果您希望数据获取Date_Enter
最大的记录,则在该列上应用order by。如果您想通过multiple order condition
获取记录,那么您还可以在多个列上应用订单。
仅按日期排序_Enter:
SELECT TOP 1
ID_RE
Date_Enter,
Date_Process,
Date_Shipment,
Description
FROM Reports
ORDER BY Date_Enter DESC
使用Date_Enter,Date_Process和Date_Shipment排序:
SELECT TOP 1
ID_RE
Date_Enter,
Date_Process,
Date_Shipment,
Description
FROM Reports
ORDER BY Date_Enter DESC, Date_Process DESC, Date_Shipment DESC
答案 1 :(得分:0)
<强>问题:强>
你写的查询不正确。我建议你阅读SQL中的GROUP BY
注意:您的问题数据中存在以下两个问题。
1- Date_Shipment不是正确的日期,因为209不是有效年份
2- [Date_Shipment]的数据类型为VARCHAR
,应为DATETIME
,
insert into Reports(Date_Enter,Date_Process,Date_Shipment,Description) values('2013-02-01 01:52:23','2008-04-01 12:45:23','209-02-01 07:35:43','It is For trade')
解决方案:
如果你想根据所有3列找到MAX
并根据它来决定,你可以写下面的查询。
SELECT
ID_RE,
(SELECT MAX(MaxDate)
FROM (VALUES (Date_Enter),(Date_Process),(Date_Shipment)) AS FindMax(MaxDate))
AS MaxDate
FROM [dbo].[Reports]
如果您想根据1个日期列查找MAX
,可以尝试以下操作。如果Date_Enter
对于2条或更多条记录相同,则以下查询将返回多条记录。
SELECT * FROM [dbo].[Reports]
WHERE Date_Enter =
(
SELECT MAX(Date_Enter) FROM [dbo].[Reports]
)
如果您只想根据Date_Enter获取1条记录,可以尝试以下内容。
SELECT TOP 1 * FROM [dbo].[Reports]
ORDER BY Date_Enter DESC