Solved

How to return a single row with a maximum column value from a sub query

Posted on 2013-12-21
10
397 Views
Last Modified: 2013-12-22
The sub-query in the following statement returns two records as given below:


                  SELECT TMP.TOTAL_ACRES, TMP.YEAR, SD1.*
                  FROM      
                  (SELECT      CA.ACCOUNT_ID, CA.YEAR - 2 AS YEAR, SUM(CA.ACRES) AS TOTAL_ACRES
                         FROM      dbo.Table1 CA INNER JOIN
                              dbo.Table2 A ON
                                    A.ACCOUNT_ID = CA.ACCOUNT_ID
                         WHERE CA.INACTIVE_FLAG IS NULL
                         GROUP BY CA.ACCOUNT_ID, CA.YEAR - 2) tmp
                  INNER JOIN
                  dbo.Table3 SD1 ON
                  tmp.ACCOUNT_ID = SD1.ACCOUNT_ID AND
                  tmp.YEAR = SD1.PROGRAM_YEAR
                  WHERE      SD1.TOTAL_ACRES IS NULL AND SD1.ACREAGE_ESTIMATED IS NULL

Again, the sub-query in the above statement returns two records as given below:

ACCOUNT_ID      YEAR      TOTAL_ACRES
10205467                        2007       1825
10205467                        2008       1825

How can I change the sub-query to only get a single record with the largest number of year, in this case year 2008, i.e. as follows:

ACCOUNT_ID      YEAR      TOTAL_ACRES
10205467                        2008       1825

Please help by changing the above query!
0
Comment
Question by:skaleem1
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
10 Comments
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39734134
If you mean one per ACCOUNT_ID then :
;WITH MyCTE AS (
 SELECT TMP.TOTAL_ACRES,
        TMP.[YEAR],
        SD1.*,
        ROW_NUMBER() OVER (PARTITION BY TMP.ACCOUNT_ID ORDER BY TMP.[YEAR] DESC) Row
 FROM   (SELECT CA.ACCOUNT_ID,
                CA.[YEAR] - 2 AS [YEAR],
                SUM(CA.ACRES) AS TOTAL_ACRES
         FROM   dbo.Table1 CA
                INNER JOIN dbo.Table2 A ON A.ACCOUNT_ID = CA.ACCOUNT_ID
         WHERE  CA.INACTIVE_FLAG IS NULL
         GROUP BY CA.ACCOUNT_ID,
                CA.YEAR - 2
        ) tmp
        INNER JOIN dbo.Table3 SD1 ON tmp.ACCOUNT_ID = SD1.ACCOUNT_ID
                                     AND tmp.[YEAR] = SD1.PROGRAM_YEAR
 WHERE  SD1.TOTAL_ACRES IS NULL
        AND SD1.ACREAGE_ESTIMATED IS NULL
        )
SELECT  *
FROM MyCTE
WHERE Row = 1

Open in new window

0
 
LVL 8

Expert Comment

by:vr6r
ID: 39734135
Try this:
SELECT TMP.TOTAL_ACRES, TMP.YEAR, SD1.*
FROM      
(SELECT TOP 1 
	CA.ACCOUNT_ID, 
	CA.YEAR - 2 AS YEAR, 
	SUM(CA.ACRES) AS TOTAL_ACRES
	FROM dbo.Table1 CA 
	INNER JOIN dbo.Table2 A ON A.ACCOUNT_ID = CA.ACCOUNT_ID 
	WHERE CA.INACTIVE_FLAG IS NULL 
	GROUP BY CA.ACCOUNT_ID, CA.YEAR - 2
	ORDER BY CA.YEAR DESC) tmp
INNER JOIN
dbo.Table3 SD1 ON
tmp.ACCOUNT_ID = SD1.ACCOUNT_ID AND 
tmp.YEAR = SD1.PROGRAM_YEAR 
WHERE      SD1.TOTAL_ACRES IS NULL AND SD1.ACREAGE_ESTIMATED IS NULL

Open in new window

0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39734137
If you mean only one row then replace:
ROW_NUMBER() OVER (PARTITION BY TMP.ACCOUNT_ID ORDER BY TMP.[YEAR] DESC) Row
For:
ROW_NUMBER() OVER (ORDER BY TMP.[YEAR] DESC) Row
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 1

Author Comment

by:skaleem1
ID: 39734148
Acperkins,

I get the following error:

The column 'TOTAL_ACRES' was specified multiple times for 'MyCTE'.
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39734179
The answer really depends on what you want to see (you have not told us).  

If just one line then:
;WITH MyCTE AS (
 SELECT TMP.[YEAR],
        TMP.TOTAL_ACRES,
--        SD1.*,
        ROW_NUMBER() OVER (ORDER BY TMP.[YEAR] DESC) Row
 FROM   (SELECT CA.ACCOUNT_ID,
                CA.[YEAR] - 2 AS [YEAR],
                SUM(CA.ACRES) AS TOTAL_ACRES
         FROM   dbo.Table1 CA
                INNER JOIN dbo.Table2 A ON A.ACCOUNT_ID = CA.ACCOUNT_ID
         WHERE  CA.INACTIVE_FLAG IS NULL
         GROUP BY CA.ACCOUNT_ID,
                CA.YEAR - 2
        ) tmp
        INNER JOIN dbo.Table3 SD1 ON tmp.ACCOUNT_ID = SD1.ACCOUNT_ID
                                     AND tmp.[YEAR] = SD1.PROGRAM_YEAR
 WHERE  SD1.TOTAL_ACRES IS NULL
        AND SD1.ACREAGE_ESTIMATED IS NULL
        )
SELECT  [YEAR], TOTAL_ACRES
FROM MyCTE
WHERE Row = 1

Open in new window

0
 
LVL 75

Accepted Solution

by:
Anthony Perkins earned 500 total points
ID: 39734183
If you want to see one row per account then change it as follows:
;WITH MyCTE AS (
 SELECT TMP.ACCOUNT_ID,
        TMP.[YEAR],
        TMP.TOTAL_ACRES,
--      SD1.*,
        ROW_NUMBER() OVER (PARTITION BY TMP.ACCOUNT_ID ORDER BY TMP.[YEAR] DESC) Row
 FROM   (SELECT CA.ACCOUNT_ID,
                CA.[YEAR] - 2 AS [YEAR],
                SUM(CA.ACRES) AS TOTAL_ACRES
         FROM   dbo.Table1 CA
                INNER JOIN dbo.Table2 A ON A.ACCOUNT_ID = CA.ACCOUNT_ID
         WHERE  CA.INACTIVE_FLAG IS NULL
         GROUP BY CA.ACCOUNT_ID,
                CA.YEAR - 2
        ) tmp
        INNER JOIN dbo.Table3 SD1 ON tmp.ACCOUNT_ID = SD1.ACCOUNT_ID
                                     AND tmp.[YEAR] = SD1.PROGRAM_YEAR
 WHERE  SD1.TOTAL_ACRES IS NULL
        AND SD1.ACREAGE_ESTIMATED IS NULL
        )
SELECT  ACCOUNT_ID, [YEAR], TOTAL_ACRES
FROM MyCTE
WHERE Row = 1

Open in new window

0
 
LVL 1

Author Closing Comment

by:skaleem1
ID: 39734192
AcPerkins,

This is what I was looking for. Thanks for the quick help.

vr6r,

Thanks for your help but unfortunately that was the solution I personally came up with but did not work.
0
 
LVL 1

Author Comment

by:skaleem1
ID: 39734197
AcPerkins,

I apologize but I forgot to mention that I originally want to write the update statement:

UPDATE SD1
                  SET      TOTAL_ACRES = tmp.TOTAL_ACRES,
                        ACREAGE_ESTIMATED = 'Y'
                  --SELECT TMP.TOTAL_ACRES, TMP.YEAR, SD1.*
                  FROM      
                  (SELECT      CA.ACCOUNT_ID, CA.YEAR - 2 AS YEAR, SUM(CA.ACRES) AS TOTAL_ACRES
                         FROM      dbo.Table1 CA INNER JOIN
                              dbo.Table2 A ON
                                    A.ACCOUNT_ID = CA.ACCOUNT_ID
                         WHERE CA.INACTIVE_FLAG IS NULL
                         GROUP BY CA.ACCOUNT_ID, CA.YEAR - 2) tmp
                  INNER JOIN
                  dbo.Table3 SD1 ON
                  tmp.ACCOUNT_ID = SD1.ACCOUNT_ID AND
                  tmp.YEAR = SD1.PROGRAM_YEAR
                  WHERE      SD1.TOTAL_ACRES IS NULL AND SD1.ACREAGE_ESTIMATED IS NULL

How can I use your with statement with this update statement?
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39734838
So you want to UPDATE all the years in Table3 with the last value from Table1 and Table2 and where you do not have a previous value for TOTAL_ACRES and ACREAGE_ESTIMATED?
0
 
LVL 75

Expert Comment

by:Anthony Perkins
ID: 39734858
If so try it like this:
SELECT	SD1.Account, 
		tmp.TOTAL_ACRES
--UPDATE  SD1
--SET     TOTAL_ACRES = tmp.TOTAL_ACRES,
--        ACREAGE_ESTIMATED = 'Y'
FROM    dbo.Table3 SD1
        INNER JOIN (SELECT  CA.ACCOUNT_ID,
                            CA.[YEAR] - 2 AS [YEAR],
                            SUM(CA.ACRES) AS TOTAL_ACRES,
                            ROW_NUMBER() OVER (PARTITION BY CA.ACCOUNT_ID, CA.YEAR ORDER BY CA.YEAR DESC) Row
                    FROM    dbo.Table1 CA
                            INNER JOIN dbo.Table2 A ON A.ACCOUNT_ID = CA.ACCOUNT_ID
                    WHERE   CA.INACTIVE_FLAG IS NULL
                    GROUP BY CA.ACCOUNT_ID,
                            CA.YEAR - 2
                   ) tmp ON SD1.ACCOUNT_ID = tmp.ACCOUNT_ID --AND SD1.PROGRAM_YEAR = tmp.[YEAR]
WHERE   COALESCE(SD1.TOTAL_ACRES, SD1.ACREAGE_ESTIMATED) IS NULL
        AND tmp.Row = 1

Open in new window


If it looks correct, then uncomment the UPDATE and comment out the SELECT.
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This is a high-level webinar that covers the history of enterprise open source database use. It addresses both the advantages companies see in using open source database technologies, as well as the fears and reservations they might have. In this…
There's a multitude of different network monitoring solutions out there, and you're probably wondering what makes NetCrunch so special. It's completely agentless, but does let you create an agent, if you desire. It offers powerful scalability …

729 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