我有以下表格:
我想得到结果:
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
我得到了结果:
我想在每行中取第2和第3列的总和(如上面预期结果中所述)。但是不能服用。
如何在查询中进行更改?什么是查询
答案 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