Efficiently convert rows to columns in sql server
There are several ways that you can transform data from multiple rows into columns.
Using PIVOT
In SQL Server you can use the PIVOT
function to transform the data from rows to columns:
select Firstname, Amount, PostalCode, LastName, AccountNumber
from
(
select value, columnname
from yourtable
) d
pivot
(
max(value)
for columnname in (Firstname, Amount, PostalCode, LastName, AccountNumber)
) piv;
See Demo.
Pivot with unknown number of columnnames
If you have an unknown number of columnnames
that you want to transpose, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName)
from yourtable
group by ColumnName, id
order by id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select value, ColumnName
from yourtable
) x
pivot
(
max(value)
for ColumnName in (' + @cols + N')
) p '
exec sp_executesql @query;
See Demo.
Using an aggregate function
If you do not want to use the PIVOT
function, then you can use an aggregate function with a CASE
expression:
select
max(case when columnname = 'FirstName' then value end) Firstname,
max(case when columnname = 'Amount' then value end) Amount,
max(case when columnname = 'PostalCode' then value end) PostalCode,
max(case when columnname = 'LastName' then value end) LastName,
max(case when columnname = 'AccountNumber' then value end) AccountNumber
from yourtable
See Demo.
Using multiple joins
This could also be completed using multiple joins, but you will need some column to associate each of the rows which you do not have in your sample data. But the basic syntax would be:
select fn.value as FirstName,
a.value as Amount,
pc.value as PostalCode,
ln.value as LastName,
an.value as AccountNumber
from yourtable fn
left join yourtable a
on fn.somecol = a.somecol
and a.columnname = 'Amount'
left join yourtable pc
on fn.somecol = pc.somecol
and pc.columnname = 'PostalCode'
left join yourtable ln
on fn.somecol = ln.somecol
and ln.columnname = 'LastName'
left join yourtable an
on fn.somecol = an.somecol
and an.columnname = 'AccountNumber'
where fn.columnname = 'Firstname'
Python Pandas: Convert Rows as Column headers
You're looking for pivot_table
:
In [11]: medals = df.pivot_table('no of medals', ['Year', 'Country'], 'medal')
In [12]: medals
Out[12]:
medal Bronze Gold Silver
Year Country
1896 Afghanistan 3 5 4
Algeria 3 1 2
and if you want to reorder the columns:
In [12]: medals.reindex_axis(['Gold', 'Silver', 'Bronze'], axis=1)
Out[12]:
medal Gold Silver Bronze
Year Country
1896 Afghanistan 5 4 3
Algeria 1 2 3
How can I transform rows to columns?
use:
={"Date"\ "Type"\ "Metric"; INDEX(QUERY(SPLIT(
FLATTEN(A2:A6&"×"&B1:L1&"×"&B2:L6); "×");
"where Col3 is not null"; ))}
Convert rows to columns and group
Why not a conditional aggregation
SELECT Comedor = com.NombrePuntoEntrega
,APLICACIONES = SUM(case when a.NombreArea = 'APLICACIONES' then s.CantidadRaciones else 0 end)
,ARANDANOS = SUM(case when a.NombreArea = 'ARANDANOS' then s.CantidadRaciones else 0 end)
,PALTO = SUM(case when a.NombreArea = 'PALTO' then s.CantidadRaciones else 0 end)
FROM PPA_SolicitudRaciones c inner join
PPA_SolicitudRacionesDET S on c.IdSolicitud =s.IdSolicitud and s.IdLocalidad =c.IdLocalidad
INNER JOIN PPA_AREAS A ON A.IDLOCALIDAD=S.IDLOCALIDAD and a.IdArea =s.IdArea
INNER JOIN PPA_PuntosEntrega com on com.IdLocalidad =s.IdLocalidad and com.IdPuntoEntrega =s.IdPuntoEntrega
WHERE (s.IdLocalidad =@IdLocalidad or @IdLocalidad =0)
AND (s.IdArea =@IdArea or @IdArea =0)
AND (c.FechaPedido between @FechaDel and @FechaAl or @FechaDel ='1900.01.01' )
AND (c.IdTipoComida =@TipoComida or @TipoComida=0)
GROUP BY com.NombrePuntoEntrega
How to convert rows to columns in a Pandas groupby?
Use pivot
to transform your dataframe:
# pivot args: 1st -> index, 2nd -> columns, 3rd -> values
>>> df.pivot(['sku_id', 'size', 'source'], 'timestamp', 'price') \
.rename_axis(columns=None).add_prefix('price on ').reset_index()
sku_id size source price on 2021-01-10 price on 2021-07-10
0 1 6.0 1 115.0 NaN
1 1 6.0 2 168.0 NaN
2 1 9.0 1 152.0 152.0
3 2 8.0 1 149.0 NaN
Related Topics
Passing Dynamic Order by in Stored Procedure
How to Drop a Unique Constraint from Table Column
How to Perform a "Like" Statement in a Ssis Expression
Ways to Validate T-SQL Queries
Generating Rows Based on Column Value
How to Use Like and in for a Where Statment
How to Get the Latest 2 Items Per Category in One Select (With MySQL)
Postgresql List and Order Tables by Size
In General, Should Every Table in a Database Have an Identity Field to Use as a Pk
SQL - Displaying Entries That Are the Max of a Count
How to Select Top 3 Values from Each Group in a Table with SQL Which Have Duplicates
Index Autoincrement for Microsoft SQL Server 2008 R2
Concatenate One Field After Group By
Select Second Most Minimum Value in Oracle
How to Have the Table Name as "Option" in MySQL
Which Is the Best Way to Form the String Value Using Column from a Table with Rows Having Same Id