在数据透视查询表中容纳行的总和

时间:2014-01-09 09:34:14

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

我有以下表格:

enter image description here

我想得到结果:

mon  QDBCount   MINISTERIALECount  Sum

Jan    5           3                8

Feb    4           9               13

Mar    6           5               11

.
.
.

注意: QDBCount和MINISTERIALECount是这两个在上表中特定月份到达的次数

为此,我做了以下查询:

select * from
(
select convert(char(4),[Data creazione pratica],100) mon  , 
[Cod# prodotto],count([Cod# prodotto]) cnt
from dbPratiche 
where Compagnia='GENERTEL'
group by [Cod# prodotto], convert(char(4),[Data creazione pratica],100)


) T 
pivot
(
 max(cnt)
 for [Cod# prodotto] 
 in ([QDB],[MINISTERIALE])
)p

我得到了结果:

enter image description here

我想在每行中取第2和第3列的总和(如上面预期结果中所述)。但是不能服用。

如何在查询中进行更改?什么是查询

2 个答案:

答案 0 :(得分:1)

嗯,这有点蹩脚,但是:

WITH ctablee (mon, qdb, ministeriale) 
     AS (SELECT "columns what you use" 
         FROM   (SELECT CONVERT(CHAR(4), [data creazione pratica], 100) mon, 
                        [cod# prodotto], 
                        Count([cod# prodotto])                          cnt 
                 FROM   dbpratiche 
                 WHERE  compagnia = 'GENERTEL' 
                 GROUP  BY [cod# prodotto], 
                           CONVERT(CHAR(4), [data creazione pratica], 100)) T 
                PIVOT ( Max(cnt) 
                      FOR [cod# prodotto] IN ([QDB], 
                                              [MINISTERIALE]) )p) 
SELECT mon, 
       qdb, 
       ministeriale, 
       ministeriale + qdb 
FROM   ctablee  

答案 1 :(得分:1)

由于您拥有的Products数量有限,您可以使用subqueries采用替代方法:

;with cte as (
 SELECT 
convert(char(4),[Data creazione pratica],100) mon
,[Cod# prodotto]
FROM dbPratiche 
WHERE Compagnia='GENERTEL'
)       
SELECT MON
,(SELECT COUNT(*) FROM cte t2 WHERE t1.mon=t2.mon and t2.cod#prodotto='qdb') qdbcount
,(SELECT COUNT(*) FROM cte t2 WHERE t1.mon=t2.mon and t2.cod#prodotto='ministeriacle')ministeriaclecount
,COUNT(*) total
FROM cte t1
GROUP BY MON