SQL Server: multiple select statements from the same table in one query The Next CEO of Stack OverflowMultiple COUNT SELECTS from the same table in one queryHow do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?Check if table exists in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?LEFT JOIN vs. LEFT OUTER JOIN in SQL ServerInserting multiple rows in a single SQL query?Update a table using JOIN in SQL Server?How do I UPDATE from a SELECT in SQL Server?

Why can't we say "I have been having a dog"?

Is there a rule of thumb for determining the amount one should accept for of a settlement offer?

Is it reasonable to ask other researchers to send me their previous grant applications?

How to pronounce fünf in 45

Find the majority element, which appears more than half the time

Do I need to write [sic] when including a quotation with a number less than 10 that isn't written out?

Masking layers by a vector polygon layer in QGIS

Incomplete cube

How should I connect my cat5 cable to connectors having an orange-green line?

Why does freezing point matter when picking cooler ice packs?

pgfplots: How to draw a tangent graph below two others?

Man transported from Alternate World into ours by a Neutrino Detector

Avoiding the "not like other girls" trope?

Is it okay to majorly distort historical facts while writing a fiction story?

What difference does it make matching a word with/without a trailing whitespace?

Shortening a title without changing its meaning

What are the unusually-enlarged wing sections on this P-38 Lightning?

Is the offspring between a demon and a celestial possible? If so what is it called and is it in a book somewhere?

What did the word "leisure" mean in late 18th Century usage?

Why did Batya get tzaraat?

Why was Sir Cadogan fired?

Can Sri Krishna be called 'a person'?

Are British MPs missing the point, with these 'Indicative Votes'?

Cannot restore registry to default in Windows 10?



SQL Server: multiple select statements from the same table in one query



The Next CEO of Stack OverflowMultiple COUNT SELECTS from the same table in one queryHow do I perform an IF…THEN in an SQL SELECT?Add a column with a default value to an existing table in SQL ServerHow to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?Check if table exists in SQL ServerHow to concatenate text from multiple rows into a single text string in SQL server?LEFT JOIN vs. LEFT OUTER JOIN in SQL ServerInserting multiple rows in a single SQL query?Update a table using JOIN in SQL Server?How do I UPDATE from a SELECT in SQL Server?










1















I'm working on two queries that pull data from one table. I can get them to run how I want individually, but I'd like to combine them into one if possible. I've tried the solution in [Multiple COUNT SELECTS from the same table in one query but wasn't able to get it figured out. Below is what I'm working on:



--goback 30 days start at midnight
declare @daysgoingback as int
set @daysgoingback = 90

declare @olderdate as datetime
set @olderdate = DATEADD(Day, -@daysgoingback, DATEDIFF(Day, 0, GetDate()))

--today at 11:59pm
declare @today as datetime
set @today = dateadd(ms, -3, (dateadd(day, +1, convert(varchar, GETDATE(), 101))))
print @today

--these are the two queries I'd like to combine:
select
avg(x.LogAlerts*1.0 / @daysgoingback) as 'Avg number of log alerts'
from
(select count(*) as LogAlerts
from message_log_table
where msg_timestamp between @olderdate and @today) X

select
avg(x.MessagesDeleted*1.0 / @daysgoingback) as 'Avg number of messages deleted'
from
(select count(*) as MessagesDeleted
from message_log_table
where msg_details like '%message deleted%'
and msg_timestamp between @olderdate and @today) X









share|improve this question
























  • Combine them how? one on top of the other? side-by-side?

    – Tab Alleman
    Mar 21 at 19:06











  • @TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

    – Jeremiah Williams
    Mar 21 at 19:08











  • Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

    – Sean Lange
    Mar 21 at 19:18















1















I'm working on two queries that pull data from one table. I can get them to run how I want individually, but I'd like to combine them into one if possible. I've tried the solution in [Multiple COUNT SELECTS from the same table in one query but wasn't able to get it figured out. Below is what I'm working on:



--goback 30 days start at midnight
declare @daysgoingback as int
set @daysgoingback = 90

declare @olderdate as datetime
set @olderdate = DATEADD(Day, -@daysgoingback, DATEDIFF(Day, 0, GetDate()))

--today at 11:59pm
declare @today as datetime
set @today = dateadd(ms, -3, (dateadd(day, +1, convert(varchar, GETDATE(), 101))))
print @today

--these are the two queries I'd like to combine:
select
avg(x.LogAlerts*1.0 / @daysgoingback) as 'Avg number of log alerts'
from
(select count(*) as LogAlerts
from message_log_table
where msg_timestamp between @olderdate and @today) X

select
avg(x.MessagesDeleted*1.0 / @daysgoingback) as 'Avg number of messages deleted'
from
(select count(*) as MessagesDeleted
from message_log_table
where msg_details like '%message deleted%'
and msg_timestamp between @olderdate and @today) X









share|improve this question
























  • Combine them how? one on top of the other? side-by-side?

    – Tab Alleman
    Mar 21 at 19:06











  • @TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

    – Jeremiah Williams
    Mar 21 at 19:08











  • Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

    – Sean Lange
    Mar 21 at 19:18













1












1








1








I'm working on two queries that pull data from one table. I can get them to run how I want individually, but I'd like to combine them into one if possible. I've tried the solution in [Multiple COUNT SELECTS from the same table in one query but wasn't able to get it figured out. Below is what I'm working on:



--goback 30 days start at midnight
declare @daysgoingback as int
set @daysgoingback = 90

declare @olderdate as datetime
set @olderdate = DATEADD(Day, -@daysgoingback, DATEDIFF(Day, 0, GetDate()))

--today at 11:59pm
declare @today as datetime
set @today = dateadd(ms, -3, (dateadd(day, +1, convert(varchar, GETDATE(), 101))))
print @today

--these are the two queries I'd like to combine:
select
avg(x.LogAlerts*1.0 / @daysgoingback) as 'Avg number of log alerts'
from
(select count(*) as LogAlerts
from message_log_table
where msg_timestamp between @olderdate and @today) X

select
avg(x.MessagesDeleted*1.0 / @daysgoingback) as 'Avg number of messages deleted'
from
(select count(*) as MessagesDeleted
from message_log_table
where msg_details like '%message deleted%'
and msg_timestamp between @olderdate and @today) X









share|improve this question
















I'm working on two queries that pull data from one table. I can get them to run how I want individually, but I'd like to combine them into one if possible. I've tried the solution in [Multiple COUNT SELECTS from the same table in one query but wasn't able to get it figured out. Below is what I'm working on:



--goback 30 days start at midnight
declare @daysgoingback as int
set @daysgoingback = 90

declare @olderdate as datetime
set @olderdate = DATEADD(Day, -@daysgoingback, DATEDIFF(Day, 0, GetDate()))

--today at 11:59pm
declare @today as datetime
set @today = dateadd(ms, -3, (dateadd(day, +1, convert(varchar, GETDATE(), 101))))
print @today

--these are the two queries I'd like to combine:
select
avg(x.LogAlerts*1.0 / @daysgoingback) as 'Avg number of log alerts'
from
(select count(*) as LogAlerts
from message_log_table
where msg_timestamp between @olderdate and @today) X

select
avg(x.MessagesDeleted*1.0 / @daysgoingback) as 'Avg number of messages deleted'
from
(select count(*) as MessagesDeleted
from message_log_table
where msg_details like '%message deleted%'
and msg_timestamp between @olderdate and @today) X






sql-server join count






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 21 at 19:26









marc_s

583k13011241270




583k13011241270










asked Mar 21 at 18:59









Jeremiah WilliamsJeremiah Williams

508




508












  • Combine them how? one on top of the other? side-by-side?

    – Tab Alleman
    Mar 21 at 19:06











  • @TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

    – Jeremiah Williams
    Mar 21 at 19:08











  • Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

    – Sean Lange
    Mar 21 at 19:18

















  • Combine them how? one on top of the other? side-by-side?

    – Tab Alleman
    Mar 21 at 19:06











  • @TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

    – Jeremiah Williams
    Mar 21 at 19:08











  • Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

    – Sean Lange
    Mar 21 at 19:18
















Combine them how? one on top of the other? side-by-side?

– Tab Alleman
Mar 21 at 19:06





Combine them how? one on top of the other? side-by-side?

– Tab Alleman
Mar 21 at 19:06













@TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

– Jeremiah Williams
Mar 21 at 19:08





@TabAlleman I'd like to combine them in the sense that MSSQL runs it as one query and returns the results side by side as if I just selected a couple of columns from a table.

– Jeremiah Williams
Mar 21 at 19:08













Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

– Sean Lange
Mar 21 at 19:18





Be careful here. You are doing some funky date math so you can use between. If you change the datatype to datetime2 your query is no longer as accurate. Between can be really problematic, especially when it comes to dates. sqlblog.org/2011/10/19/…

– Sean Lange
Mar 21 at 19:18












2 Answers
2






active

oldest

votes


















2














"AVG" is an aggregate function, which averages multiple rows. Your "select count(*)" subquery always returns exactly one row, so you are not really using the AVG function as it's intended.



You can combine the two like this:



 select count(*) * 1.0 / @daysgoingback as 'Avg number of log alerts'
, count(case when msg_details like '%message deleted%' then 1 end) * 1.0 / @daysgoingback as 'Avg number of messages deleted'
from message_log_table
where msg_timestamp between @olderdate and @today;





share|improve this answer























  • I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

    – Jeremiah Williams
    Mar 21 at 19:30


















1














Make each query into a CTE, and then CROSS JOIN them.



Both queries only return a single-cell result, so there's no need to get fancy here.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55287528%2fsql-server-multiple-select-statements-from-the-same-table-in-one-query%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    "AVG" is an aggregate function, which averages multiple rows. Your "select count(*)" subquery always returns exactly one row, so you are not really using the AVG function as it's intended.



    You can combine the two like this:



     select count(*) * 1.0 / @daysgoingback as 'Avg number of log alerts'
    , count(case when msg_details like '%message deleted%' then 1 end) * 1.0 / @daysgoingback as 'Avg number of messages deleted'
    from message_log_table
    where msg_timestamp between @olderdate and @today;





    share|improve this answer























    • I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

      – Jeremiah Williams
      Mar 21 at 19:30















    2














    "AVG" is an aggregate function, which averages multiple rows. Your "select count(*)" subquery always returns exactly one row, so you are not really using the AVG function as it's intended.



    You can combine the two like this:



     select count(*) * 1.0 / @daysgoingback as 'Avg number of log alerts'
    , count(case when msg_details like '%message deleted%' then 1 end) * 1.0 / @daysgoingback as 'Avg number of messages deleted'
    from message_log_table
    where msg_timestamp between @olderdate and @today;





    share|improve this answer























    • I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

      – Jeremiah Williams
      Mar 21 at 19:30













    2












    2








    2







    "AVG" is an aggregate function, which averages multiple rows. Your "select count(*)" subquery always returns exactly one row, so you are not really using the AVG function as it's intended.



    You can combine the two like this:



     select count(*) * 1.0 / @daysgoingback as 'Avg number of log alerts'
    , count(case when msg_details like '%message deleted%' then 1 end) * 1.0 / @daysgoingback as 'Avg number of messages deleted'
    from message_log_table
    where msg_timestamp between @olderdate and @today;





    share|improve this answer













    "AVG" is an aggregate function, which averages multiple rows. Your "select count(*)" subquery always returns exactly one row, so you are not really using the AVG function as it's intended.



    You can combine the two like this:



     select count(*) * 1.0 / @daysgoingback as 'Avg number of log alerts'
    , count(case when msg_details like '%message deleted%' then 1 end) * 1.0 / @daysgoingback as 'Avg number of messages deleted'
    from message_log_table
    where msg_timestamp between @olderdate and @today;






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 21 at 19:17









    Kevin SuchlickiKevin Suchlicki

    2,87921017




    2,87921017












    • I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

      – Jeremiah Williams
      Mar 21 at 19:30

















    • I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

      – Jeremiah Williams
      Mar 21 at 19:30
















    I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

    – Jeremiah Williams
    Mar 21 at 19:30





    I didn't realize I was using AVG incorrectly, so thank you for pointing that out. I tried your query as well, and it works exactly how I'd like it to. Thank you!

    – Jeremiah Williams
    Mar 21 at 19:30













    1














    Make each query into a CTE, and then CROSS JOIN them.



    Both queries only return a single-cell result, so there's no need to get fancy here.






    share|improve this answer





























      1














      Make each query into a CTE, and then CROSS JOIN them.



      Both queries only return a single-cell result, so there's no need to get fancy here.






      share|improve this answer



























        1












        1








        1







        Make each query into a CTE, and then CROSS JOIN them.



        Both queries only return a single-cell result, so there's no need to get fancy here.






        share|improve this answer















        Make each query into a CTE, and then CROSS JOIN them.



        Both queries only return a single-cell result, so there's no need to get fancy here.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 21 at 19:23

























        answered Mar 21 at 19:10









        Tab AllemanTab Alleman

        27.5k62442




        27.5k62442



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55287528%2fsql-server-multiple-select-statements-from-the-same-table-in-one-query%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript