PIVOT table for account data with columns for each month

。_饼干妹妹 提交于 2019-12-12 03:55:53

问题


The table I am looking in has the following columns:

department_number, amount, date_created.

I'm trying to create a table that shows the total amount for each department for each month in 2013, so it would look like this:

Department_number, Jan Amount, Feb Amount, March Amt, etc....

Is this a case for pivot tables, or should I just run a different query for each month and join them?


回答1:


Your case is certainly a candidate for using PIVOT table syntax. The below is a simple query which does pivot.

SELECT Department_number
,[January]
,[February]
,[March]
FROM (
SELECT Department_number, Amount, datename(date_created) AS month_created from <Your_Table>
) AS SOURCETABLE
PIVOT(SUM([Amount]) FOR month_created IN ([January],[February],[March])) AS PIVOTTABLE

This query assumes you have date_created column containing values Jan,Feb,March in your table. You may add more months if you need.

More on the subject - http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx




回答2:


If you want to display this in SSRS report then go for Row and Column grouping and aggregate the amount otherwise you can use Pivot Table with TSQL : How to pivot table with T-SQL?



来源:https://stackoverflow.com/questions/21163556/pivot-table-for-account-data-with-columns-for-each-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!