简体   繁体   English

sql在查询中选择最大日期

[英]sql select max date in a query

I have a query like this 我有这样的查询

SELECT DISTINCT
FND.ID_CON,
SPRT.CODE,
SPRT.NOM,
SPRT.DATE_VALUE,
COTPLACE.LIBELLE
FROM
FND,
SPRT,
CONTRACT,
COTPLACE
WHERE
FND.code=SPRT.code
and FND.cot_place=SPRT.cot_place
and FND.cot_place=COTPLACE.cot_place(+)
and FND.origine=SPRT.origine
and FND.ID_CON=CONTRACT.ID_CON
and FND.ORIGINE=CONTRACT.ORIGINE
and SPRT.code = '12345678' 
and CONTRACT.ID_CON like '%ABC123%'

.... ....

this query returns two lignes with different DATE_VALUE how to select only the line with max DATE_VALUE? 此查询返回两个具有不同DATE_VALUE的lignes如何仅选择最大DATE_VALUE的行? Thanks 谢谢

You can use max : 您可以使用max

select nom, prenom, max(date_empl)
from your_table
where your_condition
group by nom, prenom

You can use order by + LIMIT 1 : 您可以order by + LIMIT 1使用order by

select nom, prenom, date_empl
from person, employ, enterprise
where person.id= "test"
and person.id= emploi.id
and person.enterpriseName = enterprise.name
order by date_empl DESC LIMIT 1

THIS ANSWERS THE ORIGINAL VERSION OF THE QUESTION. 这回答了问题的原始版本。

This assumes that you mean that you get multiple rows for the same nom / prenom combination. 假设您的意思是您为同一nom / prenom组合获得多个行。 One typical method is: 一种典型的方法是:

select p.nom, p.prenom, max(e.date_empl)
from person p join
     employ em
     on p.id = em.id 
where p.id = 'test'
group by p.nom, p.prenom;

The enterprise table would not seem to be needed for this query. 该查询似乎不需要enterprise表。

Notes: 笔记:

  • Never use commas in the FROM clause. 请勿FROM子句中使用逗号。 Always use proper explicit JOIN syntax. 始终使用正确的显式JOIN语法。
  • Use table aliases that are abbreviations for table names. 使用表别名(表名称的缩写)。
  • Always qualify column names (especially in a query that references more than one table). 始终限定列名(尤其是在引用多个表的查询中)。
    • Don't use tables that are not needed. 不要使用不需要的表。

If you just want one row returned, you would use ORDER BY and some way of limiting the results. 如果只想返回一行,则可以使用ORDER BY和某种限制结果的方式。 The ANSI standard method is: ANSI标准方法是:

select p.nom, p.prenom, e.date_empl
from person p join
     employ em
     on p.id = em.id 
where p.id = 'test'
order by e.date_empl desc
fetch first 1 row only;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM