Adding one more column externally in query

社会主义新天地 提交于 2019-12-25 02:43:12

问题


I have following query:

WITH ctablee(mon, [<=15], [<=18], [<=20], [>20])
 AS 
(SELECT     *
 FROM         (SELECT     CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) mon, [Gruppi Min (GG Flusso/Decorrenza-->Out)], 
                          Count([Gruppi Min (GG Flusso/Decorrenza-->Out)]) cnt
               FROM          dbpratiche
               WHERE      compagnia = 'GENERTEL'
               GROUP BY [Gruppi Min (GG Flusso/Decorrenza-->Out)], CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100)
               ) T

                   PIVOT
                    (
                    sum(cnt)
                     FOR [Gruppi Min (GG Flusso/Decorrenza-->Out)] IN ([<=15], [<=18], [<=20], [>20])) p
                     )
    SELECT     mon, isnull([<=15], 0) [<=15], isnull([<=18], 0) [<=18], isnull([<=20], 0) [<=20], isnull([>20], 0) [>20], isnull([<=15] + [<=18] + [<=20] + [>20], 0) Total   

    FROM         ctablee

This results in:

I wanted to add one more column in it which comes through following query:

select 
AVG([Min (GG Flusso/Decorrenza-->Out) Cal#] ) avrage
from dbo.dbPratiche
where Compagnia='GENERTEL'
and Stato='OUT ATTIVATA'
group by  convert(char(4),[Data OUT (No Val#Vuoto)],100)

This results in column :

I just wanted to have this column (avrage) affter Total in first result.

How can i bind these two queries to have combined result.

Note: rows generated by both of the queries are equal.


回答1:


I done it by joining tables internally as:

WITH ctablee(mon, [<=15], [<=18], [<=20], [>20])
 AS 
(SELECT     *
 FROM         (SELECT     CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100) mon, [Gruppi Min (GG Flusso/Decorrenza-->Out)], 
                          Count([Gruppi Min (GG Flusso/Decorrenza-->Out)]) cnt
               FROM          dbpratiche
               WHERE      compagnia = 'GENERTEL'
               GROUP BY [Gruppi Min (GG Flusso/Decorrenza-->Out)], CONVERT(CHAR(4), [Data OUT (No Val#Vuoto)], 100)
               ) T

                   PIVOT
                    (
                    sum(cnt)
                     FOR [Gruppi Min (GG Flusso/Decorrenza-->Out)] IN ([<=15], [<=18], [<=20], [>20])) p
                     )


    SELECT    TB.mon, isnull(TB.[<=15], 0) [<=15], isnull(TB.[<=18], 0) [<=18], isnull(TB.[<=20], 0) [<=20], isnull(TB.[>20], 0) [>20], isnull(TB.[<=15] + TB.[<=18] + TB.[<=20] + TB.[>20], 0) Total   
    ,

   (
    select 
AVG(d.[Min (GG Flusso/Decorrenza-->Out) Cal#] ) avrage
from dbo.dbPratiche d,ctablee v
where 
convert(char(4),d.[Data OUT (No Val#Vuoto)],100)=TB.mon  and
d.Compagnia='GENERTEL'
and d.Stato='OUT ATTIVATA'
group by  convert(char(4),d.[Data OUT (No Val#Vuoto)],100)) as 'TK'
FROM         ctablee TB


来源:https://stackoverflow.com/questions/21041668/adding-one-more-column-externally-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!