在查询中外部添加一列

时间:2014-01-10 10:19:44

标签: sql database sql-server-2008-r2

我有以下查询:

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

这导致:

enter image description here

我想通过以下查询添加一个列:

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)

这导致列:

enter image description here

我只想让这个专栏(avrage)在第一个结果中遇到Total。

如何绑定这两个查询以获得组合结果。

注意:两个查询生成的行相等。

1 个答案:

答案 0 :(得分:0)

我是通过内部联系表来完成的:

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