IF OBJECT_ID('t') IS NOT NULL DROP TABLE t GOCREATE TABLE t ( ID INT, [Name] NVARCHAR(32), score INT, date DATETIME ) INSERT INTO t SELECT 1, N'小明', 88, '2014-09-05' UNION ALL SELECT 1, N'小明', 80, '2014-09-04' UNION ALL SELECT 1, N'小明', 95, '2014-09-03' UNION ALL SELECT 2, N'小华', 88, '2014-09-05' UNION ALL SELECT 2, N'小华', 92, '2014-09-02' WITH t1 AS ( SELECT ID,MAX(date)'date' FROM t GROUP BY id ) SELECT t.ID,t.NAME,t.score,CONVERT(VARCHAR(16),t.date,23) 'Date' FROM t INNER JOIN t1 ON t.ID = t1.ID AND CONVERT(VARCHAR(16),t.date,23) = CONVERT(VARCHAR(16),t1.date,23) ID NAME score Date ----------- -------------------------------- ----------- ---------------- 1 小明 88 2014-09-05 2 小华 88 2014-09-05
select * from t a where exists( select 1 from (select * from t) b where a.score>b.score and a .date>b.date and a.name=b.name ) 试试这个
找个效率高吗? 肯定没有用 top、order by 高
找个效率高吗? 肯定没有用 top、order by 高 是啊 好几层子查询,我其实做的是优化 原本写的就是 top、order by 效率太低了
select * from t a where not exists( select 1 from t where date>a .date and a.name=name )
效率优化首先考虑索引。 原先的查询语句是怎样的? 有没有建 (学号,时间) 索引?
原先的其实不是这个表,我这个表只是举例的。原先的是一句子查询 ,sql是这样的SELECT TOP ( 1 ) FeedbackDate FROM dbo.PTA_InterviewFeedback WHERE ( RequirementCandidateId = dbo.PTA_Requisition_Candidate.Id ) AND ( InterviewType = 'Technical Interview' ) ORDER BY CreateDate DESC
select * from 表名 where 时间列=(selct max(时间列) from 表名)
dbo.PTA_InterviewFeedback 建索引 (InterviewType,RequirementCandidateId,FeedbackDate),前两个字段也可以交换一下。又: dbo.PTA_Requisition_Candidate 是什么?如果是表为什么不出现在 FROM 子句中?
DROP TABLE t
GOCREATE TABLE t
(
ID INT,
[Name] NVARCHAR(32),
score INT,
date DATETIME
)
INSERT INTO t
SELECT 1, N'小明', 88, '2014-09-05' UNION ALL
SELECT 1, N'小明', 80, '2014-09-04' UNION ALL
SELECT 1, N'小明', 95, '2014-09-03' UNION ALL
SELECT 2, N'小华', 88, '2014-09-05' UNION ALL
SELECT 2, N'小华', 92, '2014-09-02' WITH t1 AS (
SELECT ID,MAX(date)'date' FROM t GROUP BY id
)
SELECT t.ID,t.NAME,t.score,CONVERT(VARCHAR(16),t.date,23) 'Date' FROM t INNER JOIN t1 ON t.ID = t1.ID AND CONVERT(VARCHAR(16),t.date,23) = CONVERT(VARCHAR(16),t1.date,23)
ID NAME score Date
----------- -------------------------------- ----------- ----------------
1 小明 88 2014-09-05
2 小华 88 2014-09-05
试试这个
肯定没有用 top、order by 高
肯定没有用 top、order by 高
是啊 好几层子查询,我其实做的是优化 原本写的就是 top、order by 效率太低了
其实我找个功能是写的子查询,子查询里加子查询 会不会效率太低了
这里有一个子查询,由于是对ID分组,会对其进行全表扫描:给ID加上聚集索引让其索引查找:
from t a
where not exists( select 1 from t where date>a .date and a.name=name )
原先的查询语句是怎样的?
有没有建 (学号,时间) 索引?
原先的其实不是这个表,我这个表只是举例的。原先的是一句子查询 ,sql是这样的SELECT TOP ( 1 )
FeedbackDate
FROM dbo.PTA_InterviewFeedback
WHERE ( RequirementCandidateId = dbo.PTA_Requisition_Candidate.Id )
AND ( InterviewType = 'Technical Interview' )
ORDER BY CreateDate DESC