Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8829607
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T07:52:22+00:00 2026-06-14T07:52:22+00:00

This is a subquery I have in a larger SQL script. It’s performing the

  • 0

This is a subquery I have in a larger SQL script. It’s performing the same action within multiple different CASE statements, so I was hoping I could somehow combine the action so it doesn’t have to do the same thing over and over. However, I can’t get the right results if I move the ORDER BY command outside of the CASE statements.

I’m joining 2 tables, met_data and flexgridlayers_table, on JDAY. Flexgridlayers_table has fields for JDAY and Segment, and met_data has fields JDAY, TAIR, and TDEW (in this simple example, but actually more fields). I’m running this through Matlab, so variable1 and variable2 are values set by a nested loop. I need to use CASE statements to account for the situation where variable1 is not equal to 1, then I want to output 0. Otherwise, I want to find values corresponding to a JDAY join, but the values may not be exact matches in F.JDAY and M.JDAY. I want to match on the closest <= value, so I use the ORDER BY M.JDAY DESC LIMIT 1 statement in each subquery.

The output is a table with fields JDAY (from F.JDAY), TAIR, and TDEW. Whenever I try moving the ORDER BY part outside of the CASE statements to get rid of the repeating subqueries, I get only a single row of results representing the largest JDAY. This query gives me the correct result – is there a way to optimize this?

SELECT F.JDAY, 
    CASE
        WHEN *variable1*<>1 THEN 0 
        ELSE 
            (SELECT M.TAIR 
            FROM met_data AS M
            WHERE M.Year=2000 AND M.JDAY<=F.JDAY
            ORDER BY M.JDAY DESC LIMIT 1)
    END AS TAIR,
    CASE
        WHEN *variable1*<>1 THEN 0 
        ELSE                
            (SELECT M.TDEW 
            FROM met_data AS M
            WHERE M.Year=2000 AND M.JDAY<=F.JDAY
            ORDER BY M.JDAY DESC LIMIT 1)
    END AS TDEW
FROM FlexGridLayers_table AS F
WHERE F.SEGMENT=*variable2*

Further explanation:

This query pulls all JDAY values from flexgridlayers_table, and then searches within the table met_data to find values corresponding to the closest <= JDAY values in that table. For example, consider the following flexgridlayers_table and met_data tables:

flexgridlayers_table:
Segment  JDAY
2        1.5
2        2.5
2        3.5
3        1.5
3        2.5
3        3.5

met_data:
JDAY  Year  TAIR  TDEW
1.0   2000  7     8
1.1   2000  9     10
1.6   2000  11    12
2.5   2000  13    14
2.6   2000  15    16
3.4   2000  17    18
4.0   2000  19    20

What I want (and what the query above returns) would be this, for variable1=1 and variable2=2:

JDAY  TAIR  TDEW
1.5   9     10
2.5   13    14
3.5   17    18  

I’m just wondering if there is a more efficient way of writing this query, so I’m not performing the ORDER BY command on the same list of JDAY values over and over for each TAIR, TDEW, etc. field.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T07:52:23+00:00Added an answer on June 14, 2026 at 7:52 am

    Then I would write as follows… It looks like you are looking for one “TAIR” and “TDEW” per JDAY. If that is the case, apply a LEFT JOIN to your met_data table once on the year condition and F vs M JDay values. Now normally, this would return multiple rows per “JDay”

    SELECT 
          PQ.JDay,
          PQ.MaxJDayPerFDay,
          CASE WHEN *var1* <> 1 THEN 0 ELSE M2.TAIR END TAIR,
          CASE WEHN *var1* <> 1 THEN 0 ELSE M2.TDEW END TDEW
       from 
          ( SELECT 
                  F.JDay,
                  MAX( M.JDAY ) as MaxJDayPerFDay
               from 
                  FlexGridLayers_Table F
                     JOIN met_Data M
                        ON M.Year = 2000
                        AND F.JDay >= M.JDay
               where
                  F.Segment = *var2* 
               group by
                  F.JDay ) PQ 
             JOIN Met_Data M2 
                on M2.Year = 2000 
                AND PQ.MaxJDayPerFDay = M2.JDay
    

    Now this does a pre-query by applying a MAX() JDay in the met_data ONCE and group by JDay so it will always return one record per F.JDay. So, now you have one query pre-qualified for your F.Segment = variable 2. If you had other columns you wanted from the “F” table, put them into this “PreQuery” (PQ alias) as needed.

    Then, this result can immediately be joined back to the met_data table since the one day value is now explicitly known from the prequery. So, you can now get both TAIR and TDEW values at once rather than in two separate queries being applied for every record.

    Hope this make sense, if not, let me know.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this query that inserts rows, using a subquery like so: INSERT INTO
I have a syntax error in this subquery that I cannot seem to figure
I have a SQL query that's fairly complicated and involves multiple subqueries and unions.
I dont have any idea why am i getting this error :- Subquery returned
Environment : SQL Server 2005 I have this type of request SELECT * FROM
I have a very complex MySQL query that includes use of the same subquery
I have an SQL script (currently running against SQLite, but it should probably work
I have a subquery within a WHERE-clause within a subquery. Notwithstanding the design issues
I've noticed that running this subquery SELECT ST_Area(ST_Union(ST_Transform(ST_Intersection((SELECT poly1.the_geom from poly1 WHERE poly1.polygon_type='P'),poly2.the_geom),3857))) AS
I need to rewrite this query and I'm not allowed to use a subquery.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.