Pivoting 2 column in SQL server - sql

I got result data from table B2BSALES like this
What i can do just with unpivot just like this from this query
SELECT [Date], [Desc], AREA,Value as TotalAmt
FROM [dbo].[StagingSalesB2BINDOMA]
UNPIVOT
(Value FOR AREA in
(TOTAL, Bandung, CIREBON, BANJARMASIN, BATAM, BALI)
)AS unpvt;
just get column city as area
what i want is like this
how can i do it with query , can i use join before pivoting , thanks before

You seem to want to unpivot. I recommend apply :
select t.date, t.[desc], v.area.v.amt
from t cross apply
(values ('Total', total),
('Bandung', bandung),
('Cirebon', cirebon),
. . .
) as v(area, amt);

Related

How to make rows into columns in SQL

I have this table
SELECT PolicyID, ItemID, Period, Inventory1, Inventory2
FROM tblInventory
I want to convert this table into this:
The period will be converted as Column such as Inventory1 -1 and Inventory2 -1 until 4th period, per period there are two columns included: inventory1 and inventory2.
I would like to ask help on how to code this in SQL. Thank you!
To use PIVOT with your example you want to UNPIVOT the data first.
SELECT
*
FROM
(
SELECT
UP.PolicyId
, UP.ItemId
, CONCAT(UP.Inventories, '-', UP.Period) AS Inventories
, UP.Inventory
FROM
tblInventory AS TI
UNPIVOT
(
Inventory FOR Inventories IN (Inventory1, Inventory2)
) AS UP
) AS UNP
PIVOT
(
MAX(Inventory)
FOR Inventories IN
(
[Inventory1-1], [Inventory1-2], [Inventory1-3], [Inventory1-4]
, [Inventory2-1], [Inventory2-2], [Inventory2-3], [Inventory2-4]
)
) AS PVT

How to use unpivot operator to combine rows and columns?

I need to group customers by GroupName. Customers can be duplicated on each GroupName. Each GroupName has a unique number called "GroupCode" in table OCQG. Customer table (OCRD) has separate column for Each GroupCode. As an example, C-0001 customer can have more group names.We can identify GroupCodes for each customer by see Group1,...,Group64 column values.(If this value = Y).Table structure as follows.Please help me.
I tried following query.But it didn't work.
SELECT p.CardCode, REPLACE(p.QryGroup,'GROUP','') groupcode, ocqg.GroupName
FROM ocrd UNPIVOT
( value
FOR groupcode IN ([QryGroup1],[QryGroup2],[QryGroup3])
) as p,
ocqg
WHERE value = 'Y' and
ocqg.GroupCode = REPLACE(p.groupcode,'GROUP','')
order by p.CardCode
Table Structure as follows,
I recommend using APPLY for this purpose:
SELECT ocrd.CardCode, v.groupcode, ocqg.GroupName
FROM ocrd CROSS APPLY
(VALUES (1, QryGroup1),
(2, QryGroup2),
(3, QryGroup3),
. . .
) v(GroupCode, Value) JOIN
ocqg
ON ocqg.GroupCode = v.GroupCode
WHERE v.value = 'Y'
ORDER BY p.CardCode;
UNPIVOT is bespoke syntax for SQL Server and Oracle that does one thing.
On the other hand, APPLY implements "lateral join"s.' These are very powerful -- much more powerful than UNPIVOT -- and supported by more databases.

Pivot in SQL without Aggregate function

I have a scenario Where I have a table like
Table View
and What Output I want is
If your argument is "I will only ever have one value or no values, therefore I don't want an aggregate", realise that there are several aggregates that, if they're only passed a single value to aggregate, will return that value back as their result. MIN and MAX come to mind. SUM also works for numeric data.
Therefore the solution to specifying a PIVOT without an aggregate is instead to specify such a "pass through" aggregate here.
Basically, PIVOT internally works a lot the same as GROUP BY. Except the grouping columns are all columns in the current result set other than the column mentioned in the aggregate part of the PIVOT specification. And just as with the rules for the SELECT clause when GROUP BY is used1, every column either needs to be a grouping column or contained in an aggregate.
1Grumble, grumble, older mysql grumble. Although the defaults are more sensible from 5.7.5 up.
Try this:
Demo
with cte1 as
(
select 'Web' as platformname,'abc' as productname,'A' as grade
union all
select 'Web' ,'cde' ,'B'
union all
select 'IOS' ,'xyz' ,'C'
union all
select 'MAX' ,'cde' ,'D'
)
select productname,[Web], [IOS], [Android],[Universal],[Mac],[Win32]
from cte1 t
pivot
(
max(grade)
for platformname in ([Web], [IOS], [Android],[Universal],[Mac],[Win32])
) p
You can "pivot" such data using joins:
select p.productname,
t_win32.grade as win32,
t_universal.grade as universal,
. . .
from products p left join -- assume you have such a table
t t_win32
on t_win32.product_name = p.productname and t_win32.platform = 'Win32' left join
t t_universal
on t_universal.product_name = p.productname and t_universal.platform = 'Universal' left join
. . .
If you don't have a table products, use a derived table instead:
from (select distinct product_name from t) p left join
. . .

SQL Server unpivot with multiple columns

Trying to get an Unpivot to apply across a few columns and am struggling to get it to work correctly. Maybe its not the right solution so definitely open to suggestions. Here's an example of my dataset
Sample Data Set In Excel
Sample Wanted Data Set In Excel
Sorry for the links, can't quite stick pics in these posts just yet.
Here's the code that I'm close to, it seems like I'm close...but maybe not.
SELECT
RunDate,
ShipMode,
Amt
FROM
(SELECT
CAST(sh.RunDt as DATE) as RunDt,
sh.method1, sh.method2, sh.method3,
sh.method4, sh.method5
FROM
[dbo].sampletable sh
WHERE
RunDt = '2016-10-17') AS P
UNPIVOT (
RunDate FOR ShipMode IN(method1, method2, method3,method4, method5)
) AS Unpvt
You just have a couple of names wrong. You can unpivot using the SQL:
SELECT
RunDt ,ShipMode ,Amt FROM (
SELECT
CAST(sh.RunDt as DATE) as RunDt
,sh.method1
,sh.method2
,sh.method3
,sh.method4
,sh.method5
FROM [dbo].sampletable sh
WHERE RunDt = '2018-10-17'
) AS P UNPIVOT ( Amt FOR ShipMode IN(method1, method2, method3,method4, method5) ) as Unpvt
Rather than UNPIVOT, another option is using a CROSS APPLY. It offers a bit more flexibility
Example
Select A.RunDt
,B.*
From YourTable A
Cross Apply ( values ('Method1',Method1)
,('Method2',Method2)
,('Method3',Method3)
,('Method4',Method4)
,('Method5',Method5)
) B(Overall,Amt)
Where RunDt = '2016-10-17'

Multi row to a row sql

I have a table as bellow:
I want query to print output as bellow:
Note: Please, do not downvote. I know the rules of posting answers, but for such of questions there's no chance to post short answer. I posted it only to provide help for those who want to find out how to achieve that, but does not expect ready-to-use solution.
I'd suggest to read these articles:
PIVOT on two or more fields in SQL Server
Pivoting on multiple columns - SQL Server
Pivot two or more columns in SQL Server 2005
At first UNPIVOT then PIVOT. If number of rows for each Pod_ID is not always equal 3 then you need to use dynamic SQL. The basic sample:
SELECT *
FROM (
SELECT Pod_ID,
Purs + CASE WHEN RN-1 = 0 THEN '' ELSE CAST(RN-1 as nvarchar(10)) END as Purs,
[Values]
FROM (
SELECT Pod_ID,
Pur_Qty, --All columns that will be UNPIVOTed must be same datatype
Pur_Price,
CAST(ETD_Date as int) ETD_Date, -- that is why I cast date to int
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as RN
FROM YourTable
) as p1
UNPIVOT (
[Values] FOR [Purs] IN(Pur_Qty, Pur_Price, ETD_Date)
) as unpvt
) as p2
PIVOT (
MAX([Values]) FOR Purs IN (Pur_Qty,Pur_Price,ETD_Date,Pur_Qty1,Pur_Price1,ETD_Date1,Pur_Qty2,Pur_Price2,ETD_Date2)
) as pvt
Will bring you:
Pod_ID Pur_Qty Pur_Price ETD_Date Pur_Qty1 Pur_Price1 ETD_Date1 Pur_Qty2 Pur_Price2 ETD_Date2
F8E2F614-75BC-4E46-B7F8-18C7FC4E5397 24 22 20160820 400 33 20160905 50 44 20160830