Row and column Interchange

Source: Internet
Author: User

---psydbnew (psyp_trends_getteststressoravgpoint)
SELECT Questionnum,
SUM (case when batchclassname= ' first batch ' then Avgpoint else 0 end) as ' first batch ',
SUM (case when batchclassname= ' second batch ' then Avgpoint else 0 end) as ' second batch ',
SUM (case when batchclassname= ' third batch ' then Avgpoint else 0 end) as ' The third batch ',
SUM (case when Batchclassname= ' fourth batch ' then Avgpoint else 0 end) as ' fourth instalment '
From (
SELECT DISTINCT A.testid,b.questionnum,b.questioncontent,c.totalpoint,
(1.*c.totalpoint/@TotalCount) as Avgpoint, @TotalCount as TotalCount,
Cbc. Batchclassid,c.batchclassid as TMPBATCHCLASSID,CBC. Batchclassname,
Cbc. BEGINDATE,CBC. EndDate
From V_r_reports as a
Left outer joins Psy_t_questionbase as B on A.testid=b.testid
Left outer joins #tb as C on B.testid=c.testid and B.questionnum=c.questionnum
Left outer joins Psy_u_cardbatchclass as CBC on A.UNITID=CBC. Unitid and A.BATCHCLASSID=CBC. Batchclassid
where A.unitid=ltrim (RTrim (@UnitID)) and A.testid=ltrim (RTrim (@TestID))
and A.batchclassid in (Select Distinct batchclassid from #tb_transition)
and A.staid in (Select Distinct staid from #tb_transition)
and A.departmentid in (Select Distinct DepartmentID from #tb_transition)
and A.areaid in (Select Distinct areaid from #tb_transition)
and A.sex in (Select Distinct Sex from #tb_transition)
and A.aid in (Select Distinct Ageid from #tb_transition)) as TBS
GROUP by Questionnum
---psydbnew (psyp_trends_getteststressoravgpoint)
Splitting the results--------columns
There are table TB, as follows:
ID value
----------- -----------
1 AA,BB
2 AAA,BBB,CCC
To split the value column by ID, the result is as follows:
ID value
----------- --------
1 AA
1 BB
2 AAA
2 BBB
2 CCC

--1. Old workaround (SQL Server 2000)

CREATE TABLE TB (ID int,value varchar (30))
INSERT into TB values (1, ' AA,BB ')
INSERT into TB values (2, ' AAA,BBB,CCC ')
Go

--Method 1. Using temporary table completion
SELECT TOP 8000 id = IDENTITY (int, 1, 1) to # from syscolumns A, syscolumns b

SELECT a.id, value = SUBSTRING (A.[value], b.id, CHARINDEX (', ', a.[value] + ', ', b.id)-b.id)
From TB A, # B
WHERE SUBSTRING (', ' + a.[value], b.id, 1) = ', '

DROP TABLE #

--Method 2. If the amount of data is small, temporary tables are not used
Select a.id, value = substring (a.value, B.number, charindex (', ', A.value + ', ', B.number)-B.number)
From TB a join master: Spt_values b
On b.type= ' P ' and b.number between 1 and Len (a.value)
where substring (', ' + A.value, b.number, 1) = ', '

--2. New workaround (SQL Server 2005)
CREATE TABLE TB (ID int,value varchar (30))
INSERT into TB values (1, ' AA,BB ')
INSERT into TB values (2, ' AAA,BBB,CCC ')
Go

--Method 1. Using XML to complete
SELECT a.id, B.value from
(
SELECT ID, [value] = CONVERT (XML, ' <root><v> ' + REPLACE ([value], ', ', ' </v><v> ') + ' </v> </root> ') from TB
) A OUTER APPLY
(
SELECT value = N.v.value ('. ', ' varchar ') from a.[value].nodes ('/root/v ') N (v)
) B

--Method 2. Using a CTE to complete
; with TT as
(Select Id,[value]=cast (Left ([Value],charindex (', ', ' [value]+ ', ')-1) as nvarchar (+)), split=cast (Stuff ([value]+ ', ' , 1,charindex (', ', [value]+ ', '), ') as nvarchar ()) from TB
UNION ALL
Select Id,[value]=cast (Left (Split,charindex (', ', Split)-1) as nvarchar), split= cast (Stuff ("Split,1,charindex", ', Split), ') as nvarchar (+)) from TT where Split> '
)
Select Id,[value] from the TT ORDER by ID option (maxrecursion 0)


DROP TABLE TB

----------A career change (column is dynamic)
CREATE TABLE TB (CP varchar (3), xm01 int,xm02 int,xm03 int,xm04 int)
INSERT INTO TB
Select ' CP1 ', 100,200,300,400 UNION ALL
Select ' Cp2 ', 10,20,30,40 UNION ALL
Select ' CP3 ', 11,22,32,42 UNION ALL
Select ' CP4 ', 112,222,321,422
---Method 1
SELECT * FROM TB
Select CP,XM,SL from TB
Unpivot
(SL for XM in (XM01,XM02,XM03,XM04)
) T
----Method 2
DECLARE @sql varchar (8000)
Select @sql = isnull (@sql + ' union All ', ') + ' select CP, [XM] = ' + QuoteName (Name, ' "') + ', [s1] = ' + Quoten Ame (Name) + ' from TB '
From syscolumns
where name! = N ' cp ' and ID = object_id (' TB ')--table name TB, not including other columns named CP
ORDER BY colid ASC
EXEC (@sql + ' ORDER by CP,XM ')


---career
If not object_id (' Class ') is null
drop table Class
Go
Create table Class ([Student] nvarchar (2), [Math] int,[physics] int,[English] int,[language] int)
Insert Class
Select N ' John Doe ', 77,85,65,65 UNION ALL
Select N ' Zhang San ', 87,90,82,78

----implementation
declare @s nvarchar (4000)
Select @s=isnull (@s+ ', ', ') +quotename (Name)
From syscolumns where id=object_id (' Class ') and Name is not in (' Student ')
ORDER BY Colid
EXEC (' Select Student,[course],[score] from Class Unpivot ([score] for [Course] in ('[email protected]+ ')) B ')

Go
Select
Student,[course],[score]
From
Class
Unpivot
([score] for [Course] in ([Mathematics],[Physics],[English],[language]) b

----Dynamic Row to column
CREATE table TB (Title nvarchar (20))
INSERT into TB values (N ' title 1 ')
INSERT into TB values (N ' Title 2 ')
INSERT into TB values (N ' title 3 ')
INSERT into TB values (N ' Title 4 ')
INSERT into TB values (N ' title 5 ')
Go

declare @sql nvarchar (4000)
Select @sql = isnull (@sql + '],[', ') + title from (select top of * from TB Order by title) T GROUP by title
Set @sql = ' [' + @sql + '] '
EXEC (' select * from ' (select top of * from TB Order by title) a pivot (max (title) to title in (' + @sql + ')) B ')

DROP table TB

/*--Common stored procedure for the interchange of Rows and columns (original: Jiangjian): Swaps the specified table by the specified field.
Create proc P_zj
@tbname sysname,--the name of the table to be processed
@fdname sysname,--the column name to be converted
@new_fdname sysname= '--Specify the column name for the converted Column
As
DECLARE @s1 varchar (8000), @s2 varchar (8000),
@s3 varchar (8000), @s4 varchar (8000),
@s5 varchar (8000), @i varchar (10)
Select @s1 = ', @s2 = ', @s3 = ', @s4 = ', @s5 = ', @i = ' 0 '
Select @s1 = @s1 + ', @ ' + @i + ' varchar (8000) ',
@s2 = @s2 + ', @ ' + @i + ' = ' + Case IsNull (@new_fdname, ") when" then "
else @new_fdname + ' = ' end + ' ' + ' + ' + ' ',
@s3 = @s3 + ' SELECT @ ' + @i + '[email protected]' + @i + ' + ', [' + [' + @fdname +
']+ ']= ' +cast ([' + name + '] as varchar) from [' + @tbname + '] ',
@s4 = @s4 + ', @ ' + @i + ' = ' SELECT '[email protected]' + @i,
@s5 = @s5 + ' + ' UNION ALL '[email protected]' + @i,
@i=cast (@i as int) +1
From syscolumns
where OBJECT_ID (@tbname) =id and name<> @fdname

Select @s1 =substring (@s1, 2,8000),
@s2 =substring (@s2, 2,8000),
@s4 =substring (@s4, 2,8000),
@s5 =substring (@s5, 16,8000)
EXEC (' Declare ' + @s1 + ' SELECT ' + @s2 + @s3 + ' SELECT ' + @s4 + '
EXEC (' + @s5 + ') ')
Go

--Create test data
CREATE TABLE Test (month varchar (4), payroll int, benefit int, bonus int)
Insert Test
Select ' January ', 100,200,300 UNION ALL
Select ' February ', 110,210,310 UNION ALL
Select ' March ', 120,220,320 UNION ALL
Select ' April ', 130,230,330
Go

--Use the stored procedure above to test:
exec p_zj ' Test ', ' Month ', ' project '

drop table Test
drop proc P_zj

/*
Project January February March April
--------  ------   -------- -------- --------
Bonus 300 310 320 330
Wages 100 110 120 130
Welfare 200 210 220 230

(The number of rows affected is 3 rows)

Row and column Interchange

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.