Click here to Skip to main content
14,694,465 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.
Posted

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



Directly runt the above Above script in ssms,it could give you the solution.
   
Comments
chetan virkar 28-Jan-14 2:23am
   
I want dynamic column in pivot function.
it only select distinct MonthName from table
Hi,Chetan.


You may use Pivot option for that.
   
Comments
chetan virkar 28-Jan-14 1:40am
   
Thank you Prasad I see the code for pivot and I used that
and create a query which is as follow :

<pre lang="SQL">SELECT *
FROM (
select SUM(TD.Value)Value, CONVERT(varchar(3),Td.Date,0) + '-' + CONVERT(varchar(4),YEAR(TD.Date)) [Month]
from A TD
Join B CP on TD.Type= Cp.Type
Group by CP.Type,TD.Date
) as s
PIVOT
(
SUM(Value)
FOR [month] IN ([Oct-2013],[Nov-2013],[Dec-2013],[Jan-2014]) // here I want to put dynamically the column name should be distinct Month Name from S alies but its not take that
)AS p
</pre>

I want to put column name dynamically in pivot
can this is possible?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900