[英]How to combine multiple SQL queries on one table into one report
我看過子查詢、聯合和連接。 他們似乎無法產生我正在尋找的東西,或者也許我沒有正確使用它們。
我正在使用 SQL Server 2016。
這是我所擁有的。 一個表 ( StoreScan
),其中一行是商店編號,然后是一堆其他行,其中包含每個商店收集的數據。
例子:
StoreNumber, uptime, service1status, service2status
示例數據:
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
我有幾個像這樣的小查詢:
select storenumber, uptime
from storescan
where uptime > 7
select storenumber, service1status
from storescan
where service1status = 'stopped'
我想將它們全部合並到一個查詢中,以獲得如下所示的報告:
Storenumber uptime service1status service2status
-----------------------------------------------------------
1 10
18 25
88 stopped
103 stopped
553 stopped
18 stopped
做條件聚合:
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.