简体   繁体   中英

SQL query to find last day code was used

I want to run a query to find out the last day a code was used by each Company.

SELECT T1.comp, T1,code, T1 date
FROM T1

I want to add MAX to T1.date but unsure of the sytax ... or something similar

Perhaps I can create a DATE field by concatenating T1.period & T1,yr but struggle with syntax ..

DateValue(Str(T1.period) & Str(T1.yr))

Much appreciated!

Order the table on the date descending, and keep only the first row:

SELECT TOP 1 T1.comp, T1.code, T1.date
FROM T1
ORDER BY T1.date DESC

You need an aggregate function. you can find more details here: http://www.sqlcourse2.com/agg_functions.html

for the mean time try:

SELECT T1.comp, max(T1 date)
FROM T1
GROUP BY t1.comp

By the comments on @ThomasG answer I assume you want the max for each comp that has more then 300 records?

If so, use GROUP BY and HAVING :

SELECT T1.comp, max(T1 date)
FROM T1
GROUP BY t1.comp
HAVING COUNT(*) >= 300

try this,

SELECT T1.comp, T1.code, MAX(T1.date) AS LastDate
FROM T1
GROUP BY T1.comp, T1.code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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