Sunday, February 5, 2023

SQL Server – Ultimate Pivot

Pivot


Here is the good example of SQL Pivot and Unpivot, by this we can save the efforts by using MS Excel in context to SQL data.

https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver15


An example of an Arabic Table


--- fake temporary table 


CREATE TABLE #Lazeeza_Dishes_Sale_Count(

  [Dish_Name] VARCHAR(50),

  [Month] CHAR(3),

  [Count] INT

)

GO

 

INSERT INTO #Lazeeza_Dishes_Sale_Count VALUES 

('Fattoush','Jan',145),

('Fattoush','Feb',178),

('Fattoush','Mar',198),

('Fattoush','Apr',185),

('Ful','Jan',205),

('Ful','Feb',199),

('Ful','Mar',152),

('Ful','Apr',127),

('Hummus','Jan',122),

('Hummus','Feb',131),

('Hummus','Mar',137),

('Hummus','Apr',212),

('Falafel','Jan',179),

('Falafel','Feb',109),

('Falafel','Mar',193),

('Falafel','Apr',160)

GO



SELECT * FROM (

  SELECT

    [Dish_Name],

    [Month],

    [Count]

  FROM #Lazeeza_Dishes_Sale_Count

) SaleResult

PIVOT (

  SUM([Count])

  FOR [Month]

  IN (

    [Jan],

    [Feb],

    [Mar],

    [Apr]

  )

) AS PivotTable




Additionally,


Empezar  - Is just a Spanish word "To Start / Begin" for understanding Pivot concept.


Thanks with Regards


Amit


Note: This has been modified and Republished from 20/11/2022 11:01PM

1 comment:

Anonymous said...

Going for Char, Varchar & CLR