Skip to content
Advertisement

How to merge SQL Select queries?

I have three queries executed consistently:

SELECT TOP 1 max(value) FROM tableA
where site = 18
    and (CAST(DATEADD(s,t_stamp/1000,'1970-01-01 00:00:00') as DATE) >= '2017-2-1'
    and CAST(DATEADD(s,t_stamp/1000,'1970-01-01 00:00:00') as DATE) <= '2017-2-28')
Group by CAST(DATEADD(s,t_stamp/1000,'1970-01-01 00:00:00') as DATE)
order by CAST(DATEADD(s,t_stamp/1000,'1970-01-01 00:00:00') as DATE) DESC;

SELECT TOP 1 max(value) FROM tableA
where site = 3
    and (CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) >= '2017-2-1'
    and CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) <= '2017-2-28')
Group by CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE)
order by CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) DESC;

SELECT TOP 1 max(value) FROM tableA
where site = 4
    and (CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) >= '2017-2-1'
    and CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) <= '2017-2-28')
Group by CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE)
order by CAST(DATEADD(s,stamp/1000,'1970-01-01 00:00:00') as DATE) DESC;

I want to combine this three queries into one and query sites 18, 3, 4 via one select, but I don’t see how. Please advise how to merge this 3 queries into one. Any help will be appreciated!

Advertisement

Answer

You seem to want the maximum value for three different sites on the last day in February that has their data.

If so, this is simpler:

select site_id, max(value)
from (select t.*,
             dense_rank() over (partition by site order by tstamp / (1000 * 24 * 60 * 60) desc) as seqnum
      from t
      where tstamp >= datediff(second, '1970-01-01', '2020-02-01') * 1000 and
            tstamp < datediff(second, '1970-01-01', '2020-02-29') * 1000 and
            site_id in (18, 3, 4)
     ) t
where seqnum = 1;

Actually, February in 2020 has 29 days. Perhaps you want the entire month; if so, then use '2020-03-01' for the second comparison.

Note that the manipulations on the date/time values are only on the “constant” side. This allows the query to use an index on tstamp if an appropriate index is available.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement