SQL:带有order by的条件插入

时间:2016-11-02 06:49:49

标签: mysql sql sql-server

嗨,我这里有item about insert if not exists。我想知道的一件事是,如果我想通过使用ResultDate的订单从 CompResults 获取最新项目,要插入到竞争对手表中,我应该怎么做?

INSERT Competitors (cName)
SELECT DISTINCT Name
FROM CompResults cr
WHERE
   NOT EXISTS (SELECT * FROM Competitors c
              WHERE cr.Name = c.cName) ORDER BY cr.ResultsDate DESC

发生错误:如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

3 个答案:

答案 0 :(得分:1)

您好,您必须使用select语句中的字段顺序我认为您正在使用sql server
所以你可以使用子查询

INSERT Competitors (cName)
select Name
from (
SELECT cr.Name,max(cr.ResultDate)
FROM CompResults cr
WHERE NOT EXISTS (SELECT * FROM Competitors c
WHERE cr.Name = c.cName) group BY cr.name) as t order by ResultDate

答案 1 :(得分:0)

使用Row_Number获取每个项目的最新记录

Insert into Competitors(col1,col2..)
Select col1,col2,..
(
Select row_number()Over(partition by Name order by ResultDate desc) Rn, *
From CompResults  cr
NOT EXISTS (SELECT 1 FROM Competitors c
              WHERE cr.Name = c.cName)

) a
Where Rn = 1

答案 2 :(得分:0)

你也可以如下:

INSERT Competitors (cName)
SELECT
    A.Name
FROM
    CompResults A INNER JOIN 
    (
        SELECT
            CR.Name,
            MAX(CR.ResultsDate) MaxResultsDate
        FROM
            CompResults CR
     ) B ON A.Name = B.Name AND A.ResultsDate = B.MaxResultsDate
WHERE   
   NOT EXISTS (SELECT 1 FROM Competitors c
              WHERE c.cName = A.Name)