Solved

SQL SERVER - Help with subquery - calculate max value in a range

Posted on 2013-11-27
2
332 Views
Last Modified: 2013-12-02
Hi.. I have the following code which is a solution to another question.
I need to include a column that gives me the job with the max miles and number of mles.
Any ideas?  

The result looks like this  (see code below)

CAR   LOGDATE          
FORD     2013-11-21             500
FORD     2013-11-22             600

I NEED TO INCLUDE THE MAX MILES AND JOB NUMBER LIKE THIS

CAR   LOGDATE            TOTAL MILES            JOB   MAX MILES
FORD     2013-11-21             500                   3            261
FORD     2013-11-22             600                   5            400

HERE'S THE CODE

declare @logbook table (Car varchar(50), LogDate DateTime, Job_no int, OdometerReadingEOJ int);

insert into @logbook values ('FORD', '21-Nov-2013', 1, 67);
insert into @logbook values ('FORD', '21-Nov-2013', 2, 239);
insert into @logbook values ('FORD', '21-Nov-2013', 3, 500);
insert into @logbook values ('FORD', '22-Nov-2013', 4, 700);
insert into @logbook values ('FORD', '22-Nov-2013', 5, 1100);



select t1.Car
     , t1.LogDate
     , MAX(t1.OdometerReadingEOJ) - IsNull((SELECT top 1 OdometerReadingEOJ FROM @logbook i2 WHERE i2.Car = t1.Car AND i2.LogDate < t1.LogDate ORDER BY i2.Job_no desc), 0)
  from @logbook t1
 group by t1.Car, t1.LogDate
 order by t1.Car, t1.LogDate
0
Comment
Question by:JElster
2 Comments
 
LVL 15

Assisted Solution

by:gplana
gplana earned 250 total points
ID: 39680742
I don't know the name of the fields of the original tables, but I think you need something like this:

select t1.Car
     , t1.LogDate
     , MAX(t1.OdometerReadingEOJ) - IsNull((SELECT top 1 OdometerReadingEOJ
     , job
     , MAX(miles)
 FROM @logbook i2 WHERE i2.Car = t1.Car AND i2.LogDate < t1.LogDate ORDER BY i2.Job_no desc), 0)
  from @logbook t1
 group by t1.Car, t1.LogDate
 order by t1.Car, t1.LogDate 

Open in new window

0
 
LVL 69

Accepted Solution

by:
ScottPletcher earned 250 total points
ID: 39685589
I think you'll get best overall performance and ease of coding if you put the initial results into a table, then do the final query from that table.  For example:


declare @logbook table (Car varchar(50), LogDate DateTime, Job_no int, OdometerReadingEOJ int,
    PRIMARY KEY (Car, Job_no));
declare @logbook_day table (Id int IDENTITY(1, 1) NOT NULL, Car varchar(50) NOT NULL, LogDate datetime NOT NULL, Job_no int NOT NULL, OdometerReadingEOJ int NULL,
    PRIMARY KEY (Car, Id));

insert into @logbook values ('FORD', '20131121', 1, 67);
insert into @logbook values ('FORD', '20131121', 2, 239);
insert into @logbook values ('FORD', '20131121', 3, 500);
insert into @logbook values ('FORD', '20131122', 4, 700);
insert into @logbook values ('FORD', '20131122', 5, 1100);

insert into @logbook_day ( Car, LogDate, OdometerReadingEOJ, Job_no )
select t1.Car
     , t1.LogDate
     , MAX(OdometerReadingEOJ) AS OdometerReadingEOJ
     , MAX(Job_no) AS Job_no
 from @logbook t1
 group by t1.Car, t1.LogDate
 order by t1.Car, t1.LogDate
 
 --select * from @logbook_day
 
select ld.Car
     , ld.LogDate
     , ld.OdometerReadingEOJ - ISNULL((select OdometerReadingEOJ from @logbook_day ld2 where ld2.Car = ld.Car and ld2.Id = ld.Id - 1), 0) AS [TOTAL MILES]
     , ld.Job_no AS [JOB]
     , ld.OdometerReadingEOJ - (SELECT MAX(OdometerReadingEOJ) from @logbook l where l.Car = ld.Car and l.Job_no < ld.Job_no) AS [MAX MILES]
from @logbook_day ld
order by ld.Car, ld.LogDate
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
SQL Query Syntax Error 9 34
using t-sql EXISTS 8 24
sql query Help 12 34
Convert SP in a format for debugging 7 13
Audit has been really one of the more interesting, most useful, yet difficult to maintain topics in the history of SQL Server. In earlier versions of SQL people had very few options for auditing in SQL Server. It typically meant using SQL Trace …
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now