将行数据转换为Sql Server中的列

问题描述:

大家好,



我有两个表A和表B

表A:列名1)值2)类型3 )日期

表B:列名1)类型



当我加入这两个表时,我得到了以下输出



价值|日期

1 | 2013-01-01

5 | 2013-01-02

3 | 2013-01-10

1 | 2013-02-01

2 | 2013-02-12

5 | 2013-02-25

1 | 2013-03-10

4 | 2013-03-12

3 | 2013-03-15

1 | 2013-04- 01



现在我想在表格上做一些查询,输出应该是



ColumnName:

2013年1月| 2013年2月| 2013年3月| 2013年4月

9 | 8 | 8 | 1



它显示列日期下的所有不同月份名称和总和所有值列。



任何人都可以告诉我该怎么做?



谢谢

Chetan V.

Hello Everyone,

I have two table A And Table B
Table A : Column Name 1) Value 2)Type 3) Date
Table B : Column Name 1)Type

When I joined this two table I got following output

Value | Date
1 |2013-01-01
5 |2013-01-02
3 |2013-01-10
1 |2013-02-01
2 |2013-02-12
5 |2013-02-25
1 |2013-03-10
4 |2013-03-12
3 |2013-03-15
1 |2013-04-01

Now I want to do the some query on table that the output should be

ColumnName :
Jan-2013 | Feb-2013 | Mar-2013 | Apr-2013
9 | 8 | 8 | 1

That it show all distinct month name which under column date and sum all value column.

Can any one tell me how should I do this?

Thanks
Chetan V.

PIVOT TABLE EXAMPLE

PIVOT TABLE EXAMPLE
CREATE TABLE #TempPrasad
(
Val int,
Dt DATETIME
)

INSERT INTO #TempPrasad VALUES(2,'1/1/2013')
INSERT INTO #TempPrasad VALUES(1,'1/1/2013')
INSERT INTO #TempPrasad VALUES(2,'1/1/2013')
INSERT INTO #TempPrasad VALUES(1,'2/1/2013')
INSERT INTO #TempPrasad VALUES(2,'3/1/2013')
INSERT INTO #TempPrasad VALUES(4,'3/1/2014')

--SELECT * FROM #TempPrasad

SELECT *
FROM (
    SELECT
        left(datename(month,dt),3)as [month],
        Val
    FROM #TempPrasad
) as s
PIVOT
(
    SUM(Val)
    FOR [month] IN (jan, feb, mar, apr,
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pivott


DROP TABLE #TempPrasad







直接贬低abo在ssms上面的脚本中,它可以为您提供解决方案。




Directly runt the above Above script in ssms,it could give you the solution.


您好,Chetan。





你可以使用Pivot选项。
Hi,Chetan.


You may use Pivot option for that.