透视列并根据计数显示数据

时间:2014-01-02 07:19:35

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

我有以下表格:

enter image description here

我想根据> 10,< = 06等

的组来调整月份列并显示数据计数。

意味着希望在Jun,jan

中显示> 10的计数

如下:

Gruppi Min (GG Flusso/Decorrenza-->Out)   Jan Feb Mar Apr May Jun

>10                                        5   2  1   0    8  2

<=06                                       2  8   1   7    9  33

我尝试如下:

SELECT * 
FROM   (SELECT CONVERT(CHAR(3), [data out (no val#vuoto)], 0) month, 
               ( [gruppi min (gg flusso/decorrenza-->out)] ) 
        FROM   dbpratiche 
        WHERE  compagnia = 'GENERALI INA ASSITALIA' 
               AND stato = 'OUT ATTIVATA' 
               AND [data out (no val#vuoto)] > '01-01-2012') TLB 
       PIVOT ( Count([gruppi min (gg flusso/decorrenza-->out)] ) 
             FOR tlb.month IN([jan], 
                              [feb], 
                              [mar], 
                              [apr], 
                              [may], 
                              [jun]) )PVT 

但给了我以下结果:

enter image description here

根据&gt; 10,&lt; = 06等不进行分组。并显示整体计数。

我犯了错误?

请帮帮我。

3 个答案:

答案 0 :(得分:3)

这有效

SELECT *
FROM 
(SELECT 1 CntCol, [Gruppi Min (GG Flusso/Decorrenza-->Out)], [month]
FROM #X) TLB
PIVOT
(
COUNT (CntCol)
FOR TLB.[month] IN
( [jan],[feb],[mar],[apr],[may],[jun] )
) AS pvt

您需要添加一个应该计算的列。

请看这里的复杂示例: http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

将您的代码更改为:

SELECT * 
FROM   (SELECT 1 CntCol, CONVERT(CHAR(3), [data out (no val#vuoto)], 0) month, 
               ( [gruppi min (gg flusso/decorrenza-->out)] ) 
        FROM   dbpratiche 
        WHERE  compagnia = 'GENERALI INA ASSITALIA' 
               AND stato = 'OUT ATTIVATA' 
               AND [data out (no val#vuoto)] > '01-01-2012') TLB 
       PIVOT ( Count(CntCol) 
             FOR tlb.month IN([jan], 
                              [feb], 
                              [mar], 
                              [apr], 
                              [may], 
                              [jun]) )PVT 

答案 1 :(得分:2)

您可以在dbPratiche表中添加一个自动增量字段(例如id),然后尝试以下代码:

    select * from 
    (
       select [id], [month],  [gruppi]   
       from dbPratiche 
    )as s
    pivot
    (
       COUNT ([id])
       for month in(jun, sep, jul, may, aug)
    )as PVT

答案 2 :(得分:1)

检查这可能会对你有所帮助

SELECT *
FROM (
    SELECT 
        year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month], 
        InvoiceAmount as Amount 
    FROM Invoice
) as s
PIVOT
(
    SUM(Amount)
    FOR [month] IN (jan, feb, mar, apr, 
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pivot