How to write vertical columns [duplicate] - sql

This question already has answers here:
Understanding PIVOT function in T-SQL
(7 answers)
Closed 3 years ago.
How can I write a vertical table horizontally with sql
  I want to make the following table like the example in the second picture
example
ı want to write

Try this
DECLARE #Sql nvarchar(max),
#DynamicColumn nvarchar(max),
#MaxDynamicColumn nvarchar(max)
SELECT #DynamicColumn = STUFF((SELECT DISTINCT', '+QUOTENAME(CAST(Col1 AS VARCHAR(50)))
FROM #Temp FOR XML PATH ('')),1,1,'')
SELECT #DynamicColumn
SET #Sql='SELECT '+ #DynamicColumn+'
FROM
(
SELECT *
FROM #Temp o
)AS src
PIVOT
(
MAX(Col2) FOR [Col1] IN ('+#DynamicColumn+')
) AS Pvt
'
EXEC (#Sql)
PRINT #Sql

Hi if understand your query i think this query can help you to get excepted result :
CREATE TABLE #TEMP (colName varchar(250), colOther varchar(250))
INSERT INTO #TEMP
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Desen', '2908A' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'Ebat', '125x200 R' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK' UNION ALL
SELECT 'ZeminRengi', 'KEMIK'
select Desen,Ebat,ZeminRengi
from #TEMP
PIVOT (
MAX(colOther)
FOR colName IN (Desen,Ebat,ZeminRengi)) AS Pvt
DROP TABLE #TEMP
See different link and google :
Understanding PIVOT function in T-SQL
MSDN
Google- search

Related

How to dynamically convert rows to columns in SQL Server

I want to convert rows to columns dynamically, for sample data I have given below query.
create table testtable
(
tableid int primary key identity(1,1),
tableDatetime datetime,
names varchar(50),
tablevalue decimal(18,9)
)
go
insert into testtable
select '2019-06-13 13:56:39.117', 'test1',23.45 union all
select '2019-06-13 13:56:39.117', 'test2',33.45 union all
select '2019-06-13 13:56:39.117', 'test3',10.45 union all
select '2019-06-13 13:56:39.117', 'test4',90.45 union all
select '2019-06-13 14:01:41.280', 'test1',33.45 union all
select '2019-06-13 14:01:41.280', 'test2',53.45 union all
select '2019-06-13 14:01:41.280', 'test3',41.45 union all
select '2019-06-13 14:01:41.280', 'test4',93.45 union all
select '2019-06-13 14:06:42.363', 'test1',30.45 union all
select '2019-06-13 14:06:42.363', 'test2',13.45 union all
select '2019-06-13 14:06:42.363', 'test3',23.45 union all
select '2019-06-13 14:06:42.363', 'test4',73.45
go
select * from testtable
I want to convert data in attached image format
Thanks,
You may try dynamic sql query as per your table structure.
GO
declare #query varchar(max)
set #query = (select stuff( (select distinct ',' + names from testtable for xml path ('')) ,1,1,'') as d)
declare #resquery nvarchar(max)
set #resquery = '
select * from (
select tableDatetime , names , tablevalue from testtable
) as d
pivot ( max(tablevalue) for names in ( ' + #query + ' ) ) as pv'
exec sp_executesql #resquery
GO
Please use this as per your table structure, this will create dynamic column names for your current table data. Which is further use in pivot to convert your rows into columns.
Mark it as accepted, or comment for further query.

Pivot table from horizontal to vertical

i have a following table of results:
What i want is a resulted table with following structure:
Is any posibility to do that with SQL?
Thanks in advance.
EDIT (SQL query with exampled temp table):
CREATE TABLE #FINAL_STACK
(
FB_DATE datetime,
FB_DESC VARCHAR(200)
)
INSERT INTO #FINAL_STACK(FB_DATE, FB_DESC)
SELECT '2017-03-09', 'D - FIZ: 1'
UNION
SELECT '2017-03-09', 'D - PRI: 1'
UNION
SELECT '2017-03-10', 'D - FIZ: 1'
UNION
SELECT '2017-03-10', 'D - PRI: 1'
UNION
SELECT '2017-03-13', 'D - FIZ: 2'
UNION
SELECT '2017-03-13', 'D - PRI: 1'
UNION
SELECT '2017-03-13', 'D - TEPAP: 1'
SELECT * FROM #FINAL_STACK
Try this:
DECLARE #DynammicTSQLStatement NVARCHAR(MAX)
,#DynamicPIVOTColumns NVARCHAR(MAX);
SET #DynamicPIVOTColumns = STUFF
(
(
SELECT ',[' + CAST([FB_DATE] AS VARCHAR(12)) + ']'
FROM #FINAL_STACK
GROUP BY [FB_DATE]
ORDER BY [FB_DATE]
FOR XML PATH('') ,TYPE
).value('.', 'NVARCHAR(MAX)')
,1
,1
,''
);
SET #DynammicTSQLStatement = N'
SELECT *
FROM
(
SELECT *
,ROW_NUMBER() OVER (PARTITION BY FB_DATE ORDER BY (SELECT 1)) AS RID
FROM #FINAL_STACK
) DS
PIVOT
(
MAX([FB_DESC]) FOR [FB_DATE] IN (' + #DynamicPIVOTColumns + ')
) PVT';
EXEC sp_executesql #DynammicTSQLStatement;
We need to perform dynamic pivot in order to be sure it will always work for different days. Also, note we are creating a row ID column using ROW_NUMBER in order to ensure all records for particular date are displayed. Otherwise, you will get only one value (for example the min or the max) depending on the PIVOT aggregate function.

MsSql "group by" result table design

How to convert Result 1 to result 2. I can not get result2 using the pivot table.
Result1
Result1 QUERY
SELECT Country,City,Count(*) as "Count"
FROM Customers
GROUP BY Country,City
Result2
There is no such feature of SQL other that PIVOT where, as you have discovered, you need to know the values up front.
This formatting is typically done in the output part of the system, such as your report engine. SSRS for example can handle this nicely & out of the box.
You would need dynamic SQL to achieve this lower down in the stack.
Try this dynamic sql
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
CREATE TABLE #Temp([Country] VARCHAR(20),[City] VARCHAR(20),[Count] INT)
INSERT INTO #Temp
SELECT 'Germany' ,'Aachen' ,1 UNION ALL
SELECT 'USA' ,'Albuquerque',1 UNION ALL
SELECT 'USA' ,'Anchorage' ,1 UNION ALL
SELECT 'Denmark' ,'Arhus' ,1 UNION ALL
SELECT 'Spain' ,'Barcelone' ,1
DECLARE #Colmn nvarchar(max),
#Sql nvarchar(max)
SELECT #Colmn=STUFF((SELECT distinct ', '+QUOTENAME([Country]) FROM #Temp
FOR XML PATH ('')),1,1,'')
SET #Sql =' SELECT Cityynames ,'+ #Colmn +' FROM
(
SELECT *,Country AS Countrynames,City AS Cityynames
FROM #Temp
)dt
PIVOT
(
MAX([Count]) FOR [Country] IN ('+#Colmn+')
) AS Pvt'
PRINT #Sql
EXEC (#Sql)

SQL Qry required to get a comma separated string from a table [duplicate]

This question already has answers here:
How to concatenate text from multiple rows into a single text string in SQL Server
(47 answers)
Closed 5 years ago.
In my database there is a table with values below
image attached
In need a qry to get the result like this
DECLARE #TAB TABLE(SIDS INT,VALUE VARCHAR(10))
INSERT INTO #TAB
SELECT 1,'ASC'
UNION ALL
SELECT 1,'ASC'
UNION ALL
SELECT 1,'ASC'
UNION ALL
SELECT 2,'SDF'
UNION ALL
SELECT 2,'SFD'
UNION ALL
SELECT 3,'ERF'
UNION ALL
SELECT 3,'ERF1'
SELECT T1.SIDS,VALUE = STUFF((SELECT ','+T2.VALUE FROM #TAB T2 WHERE T1.SIDS = T2.SIDS FOR XML PATH('')),1,1,'')
FROM #TAB T1
GROUP BY T1.SIDS
OUTPUT
SIDS VALUE
1 ASC,ASC,ASC
2 SDF,SFD
3 ERF,ERF1
Use XML query as below;
DECLARE #tblQuestion AS Table
(
SID INT,
Value VARCHAR(50)
)
INSERT INTO #tblQuestion VALUES(1,'stu')
INSERT INTO #tblQuestion VALUES(1,'vtu')
INSERT INTO #tblQuestion VALUES(1,'ztu')
INSERT INTO #tblQuestion VALUES(2,'stu')
INSERT INTO #tblQuestion VALUES(2,'vtu')
select distinct t.SID,
STUFF((SELECT distinct ', ' + t1.Value
from #tblQuestion t1
where t.SID = t1.SID
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,2,'') Value
from #tblQuestion t;
Output:

Need help on Pivot in SQL Server

Need help on pivot.. My i/p and o/p as below(pls see the attached image)..Could u pls help me on the query...
Here created sample data for getting result
IF OBJECT_ID('Tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
;WIth cte(EmployeeID, Activity_Date,Activity_Type)
AS
(
SELECT 1,'6/20/2016' ,'Mail_send' UNION ALL
SELECT 2,'6/22/2011' ,'Mail_Received' UNION ALL
SELECT 1,'10/11/2016','Mail_Replied' UNION ALL
SELECT 3,'10/31/2016','Mail_deleted' UNION ALL
SELECT 2,'2/11/2016' ,'Mail_Forwared'
)
SELECT * INTO #Temp FROM cte
We can get the result by using dynamic Sql with Pivot
DECLARE #dynamicCol nvarchar(max),
#Sql nvarchar(max)
SELECT #dynamicCol=STUFF((SELECT DISTINCT ', ' +QUOTENAME(Activity_Type) FROM #Temp
FOR XML PATH('')),1,1,'')
SET #Sql='
SELECT [EmployeeID] , '+ #dynamicCol +' From
(
SELECT * From
#temp
)AS Src
PIVOT
(
MAX([Activity_Date]) For [Activity_Type] IN ('+#dynamicCol+')
)
AS Pvt
'
PRINT #Sql
EXEC(#Sql)
Result
EmployeeID Mail_deleted Mail_Forwared Mail_Received Mail_Replied Mail_send
--------------------------------------------------------------------------------------
1 NULL NULL NULL 10/11/2016 6/20/2016
2 NULL 2/11/2016 6/22/2011 NULL NULL
3 10/31/2016 NULL NULL NULL NULL
Try the following Query, this should serve your purpose:
select * from
(select [Employee Id],Activity_Date,Activity_Type from Employee_Activity) tbl
pivot
(
max(Activity_Date) for Activity_Type in (Mail_Send,Mail_Received,Mail_Replied,Mail_deleted,Mail_Forwarded)
)as pvt