SQL Pivot还是Cross Tab?

时间:2016-12-19 11:59:22

标签: sql sql-server

select SALESTABLE.CUSTACCOUNT, 
       SALESTABLE.salesname,
       datename(month,SALESTABLE.SHIPPINGDATECONFIRMED)as Month, 
       sum(SALESLINE.LineAmount ) SaleAmount
from 
SALESTABLE
inner join SALESLINE 
    on SALESTABLE.SALESID= SALESLINE.SALESID

WHERE SUBSTRING(SALESTABLE.CUSTACCOUNT, 1,2)='O-'
group by SALESTABLE.CUSTACCOUNT, 
         SALESTABLE.salesname,
         datename(month,SALESTABLE.SHIPPINGDATECONFIRMED)
order by SALESTABLE.salesname,
         datename(month,SALESTABLE.SHIPPINGDATECONFIRMED)

我可以将此查询转换为数据透视表我想在表格的顶部显示月份名称,如列标题和LineAmount的总和,以及这些月的列

1 个答案:

答案 0 :(得分:0)

select      *

from       (select SALESTABLE.CUSTACCOUNT, 
                   SALESTABLE.salesname,
                   datename(month,SALESTABLE.SHIPPINGDATECONFIRMED)as Month, 
                   SALESLINE.LineAmount
            from 
            SALESTABLE
            inner join SALESLINE 
                on SALESTABLE.SALESID= SALESLINE.SALESID

            WHERE SUBSTRING(SALESTABLE.CUSTACCOUNT, 1,2)='O-'

            ) t pivot (sum (LineAmount) for Month in (January,February,March,April,May,June,July,August,September,October,November,December)) p