简体   繁体   English

如何将一张表上的多个 SQL 查询合并为一份报告

[英]How to combine multiple SQL queries on one table into one report

I have looked at subqueries, unions, and joins.我看过子查询、联合和连接。 They don't seem to be able to produce what I am looking for, or maybe I am not using them right.他们似乎无法产生我正在寻找的东西,或者也许我没有正确使用它们。

I'm using SQL Server 2016.我正在使用 SQL Server 2016。

Here is what I have.这是我所拥有的。 One table ( StoreScan ) with a row for store number and then a bunch of other rows with collected data on each store.一个表 ( StoreScan ),其中一行是商店编号,然后是一堆其他行,其中包含每个商店收集的数据。

Example:例子:

StoreNumber, uptime, service1status, service2status

Example data:示例数据:

Storenumber     uptime    service1status    service2status  
-----------------------------------------------------------
 1              10        Running           Running
 18             25        Running           Stopped 
 88             3         Stopped           Running
 90             1         Running           Running
 103            5         Stopped           Running
 553            2         Running           Stopped
 989            2         Running           Running

I have several small queries like this:我有几个像这样的小查询:

select storenumber, uptime 
from storescan 
where uptime > 7


select storenumber, service1status 
from storescan 
where service1status = 'stopped'

I'd like to combine them all into one query for a report that would look something like this:我想将它们全部合并到一个查询中,以获得如下所示的报告:

Storenumber     uptime    service1status    service2status  
-----------------------------------------------------------
1               10  
18              25  
88                        stopped  
103                       stopped  
553                                         stopped  
18                                          stopped 

Do conditional aggregation :条件聚合:

select Storenumber, 
       max(case when uptime > 7 then uptime end) as uptime,
       max(case when service1status = 'stopped' then service1status end),
       max(case when service2status = 'stopped' then service2status end)
from storescan ss 
group by Storenumber;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM