簡體   English   中英

將查詢合並為一個查詢

[英]Combine queries into one query

如何將這兩個查詢合並為一個查詢? 最初,我將第一個查詢的結果存儲到一個表中,然后使用第二個查詢來查詢該表,但是我不想再這樣做了。 任何建議表示贊賞。

查詢1

with base (org1, ind1, org2, ind2, org3, ind3)
as (
    --Lot of sub queries and processing
   )
SELECT org
    , ind
    , sum(count_final) AS count
FROM (
SELECT org1 as org , ind2 as ind, count(*) as count_final from base
group by org1 , ind2 
union all
SELECT org1 as org , ind3 as ind, count(*) as count_final from base
group by org1 , ind3 
union all
SELECT org2 as org , ind1 as ind, count(*) as count_final from base
group by org2 , ind1
union all
SELECT org2 as org , ind3 as ind, count(*) as count_final from base
group by org2 , ind3
union all
SELECT org3 as org , ind1 as ind, count(*) as count_final from base
group by org3 , ind1
union all
SELECT org3 as org , ind2 as ind, count(*) as count_final from base
group by org3 , ind2
) x
GROUP BY org
    , ind

查詢2

with cte as (
  select 
    ind, 
    sum(count) as tot 
  from 
    Query1Above 
  group by 
    ind
), 
xyz as (
  select 
    org as npi, 
    sum(count) as cnt 
  from 
    Query1Above 
  group by 
    org
) 
select 
  px.ind, 
  px.org, 
  '' as rank, 
  case when (px.count / cte.tot)* 100 < 2 then '<2%' when (px.count / cte.tot)* 100 >= 2 
  and (px.count / cte.tot)* 100 < 10 then '2%-10%' px.count as clm_cnt, 
  xyz.cnt as org_total 
from 
  Query1Above px 
  join cte on cte.ind = px.ind 
  join xyz on xyz.npi = px.org 
order by 
  px.org, 
  px.count desc

只需將Query1Above合並到其自己的CTE中,因為CTE可以基於定義的順序基於先前的CTE。

with base (org1, ind1, org2, ind2, org3, ind3) as (
    --Lot of sub queries and processing
   ),    
Query1Above as (
    SELECT org
        , ind
        , sum(count_final) AS count
    FROM (
        SELECT org1 as org , ind2 as ind, count(*) as count_final from base
        GROUP BY org1 , ind2 
        UNION ALL
        SELECT org1 as org , ind3 as ind, count(*) as count_final from base
        GROUP BY org1 , ind3 
        UNION ALL
        SELECT org2 as org , ind1 as ind, count(*) as count_final from base
        GROUP BY org2 , ind1
        UNION ALL
        SELECT org2 as org , ind3 as ind, count(*) as count_final from base
        GROUP BY org2 , ind3
        UNION ALL
        SELECT org3 as org , ind1 as ind, count(*) as count_final from base
        GROUP BY org3 , ind1
        UNION ALL
        SELECT org3 as org , ind2 as ind, count(*) as count_final from base
        GROUP BY org3 , ind2
        ) x
    GROUP BY org
        , ind
),    
cte as (
  select 
    ind, 
    sum(count) as tot 
  from 
    Query1Above 
  group by 
    ind
), 
xyz as (
  select 
    org as npi, 
    sum(count) as cnt 
  from 
    Query1Above 
  group by 
    org
) 

-- ...final main query...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM