Part 6 Transform rows into columns in sql server

Поделиться
HTML-код
  • Опубликовано: 31 июл 2024
  • Link for all dot net and sql server video tutorial playlists
    / kudvenkat
    Link for slides, code samples and text version of the video
    csharp-video-tutorials.blogspo...
    Healthy diet is very important both for the body and mind. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking our RUclips channel. Hope you can help.
    / @aarvikitchen5572
    This is another common sql server interview question. We will be using Countries table in this example.
    SQL to create the table
    Create Table Countries
    (
    Country nvarchar(50),
    City nvarchar(50)
    )
    GO
    Insert into Countries values ('USA','New York')
    Insert into Countries values ('USA','Houston')
    Insert into Countries values ('USA','Dallas')
    Insert into Countries values ('India','Hyderabad')
    Insert into Countries values ('India','Bangalore')
    Insert into Countries values ('India','New Delhi')
    Insert into Countries values ('UK','London')
    Insert into Countries values ('UK','Birmingham')
    Insert into Countries values ('UK','Manchester')
    Here is the interview question.
    Write a sql query to transpose rows to columns.
    Using PIVOT operator we can very easily transform rows to columns.
    Select Country, City1, City2, City3
    From
    (
    Select Country, City,
    'City'+
    cast(row_number() over(partition by Country order by Country)
    as varchar(10)) ColumnSequence
    from Countries
    ) Temp
    pivot
    (
    max(City)
    for ColumnSequence in (City1, City2, City3)
    ) Piv

Комментарии • 89

  • @krismaly6300
    @krismaly6300 10 лет назад +26

    PLEASE DON'T STOP THIS SERIES.
    THIS IS GOING TO BE VERY USEFUL FOR THE BEGINNERS AND ALSO REFRESHING FOR PROFESSIONALS

  • @bronco_billy
    @bronco_billy 2 года назад

    Time and time again I look for a video by you without doubt as my first choice! You have saved me many times over the years! Many blessings to you and yours kind sir!

  • @phillyt22
    @phillyt22 4 года назад

    Thank you very much. I’ve been using sql server for years and whenever I forget anything I know I will figure it out after reviewing your videos.

  • @justinli19901027
    @justinli19901027 8 лет назад

    highly recommended. one of the best, if not the best, sql teacher i have ever encountered

  • @dazedconfuzzed
    @dazedconfuzzed 10 лет назад +2

    Really Sir,
    Incredible style of teaching! Thank you so much.

  • @maxinxin1231
    @maxinxin1231 5 лет назад +2

    A lot of the questions below were how you would make the query dynamic so that even if you don’t know how many columns you will get you can still run the query. I recommend reading chapter 11 of the book TSQL fundamentals 3rd edition. Which provided a solution for this. You would first select distinct rows of the new columns and store it into a cursor. create a dynamic query where you store the select pivot statement into a string cursor(with the parenthesis open). And use a while loop to add each column cursor into the pivot statement cursor until all distinct new columns have been added. You close the parenthesis after the last column was added. With += N’)). Then you can execute the query using EXEC.

  • @krismaly6300
    @krismaly6300 9 лет назад

    I like this video and enjoyed watching and recommend others.
    City is hard coded I think we have to make automatically to create based on number of cities by concatenating 'City1' + 'City2' and so on
    Thanks for educating the community and appreciate your volunteership.

  • @taimoworks
    @taimoworks 9 лет назад +2

    Awesome video, I had the same question last year and my developers gave me a blind faceless look when I proposed that they come up with a sql solution...
    Thank you..

  • @babzo1
    @babzo1 10 лет назад

    Many thanks Venkat..simply the best

  • @Saurabharti
    @Saurabharti 9 лет назад +2

    This got solve one of my problem related to my project.. Thanks buddy!!

  • @drummermike5150
    @drummermike5150 5 лет назад +1

    Awesome thanks! Worked great! On to the T-SQL Fundamentals book to make it dynamic.

  • @thenuchellappen4688
    @thenuchellappen4688 2 года назад

    I could see this video prepared 7years ago, even it is so much helpful at 2021.. A big thanks for the simple explanation Ji 👍

  • @238Harmonics
    @238Harmonics 2 года назад

    your explanation is so easy to understand. thank you for refreshing my mind about how pivot and partition by work 🙂

  • @pupycron4302
    @pupycron4302 Год назад

    This is great I've worked with Pivot before but this really helps with getting the values unique to each column.

  • @nicolasrosso3800
    @nicolasrosso3800 5 лет назад +1

    You are awsome! Thanks!!

  • @NiceTechViews5403
    @NiceTechViews5403 6 лет назад

    Wow i tried a lot to solve this here ...your video really helped me :-)

  • @krismaly6300
    @krismaly6300 10 лет назад

    TEACHING is AWESOME

  • @pgadige
    @pgadige 9 лет назад +6

    Thank You for the great explanation, please find below the code for pivoting ( #pivoting ) with dynamic columns
    -- For dynamic columns
    -- set @DynamicPivotQuery with the final pivot query
    DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
    --@ColumnName is used to store the maximum number of column names
    DECLARE @ColumnName AS NVARCHAR(MAX)
    -- Creating temporary table
    select * into #tmpCountry
    from
    (select country, city, 'City' + cast(row_number() over (partition by country order by country) as varchar(45)) as ColumnSequence from countries) Countries
    select @ColumnName= COALESCE(@ColumnName+ ', ','') + QUOTENAME(columnsequence)
    from
    (
    select columnsequence from #tmpCountry
    where country =
    (select top 1 country from #tmpCountry
    group by country
    order by count(columnsequence) desc)
    ) test
    set @DynamicPivotQuery=
    'select country, ' +@ColumnName+ 'from #tmpCountry
    PIVOT
    (
    max(city)
    for ColumnSequence in (' +@ColumnName+ ')
    ) PIV'
    EXEC(@DynamicPivotQuery)

    • @igorcasian2015
      @igorcasian2015 7 лет назад

      ttansfomnb

    • @AJITSINGH-he6uh
      @AJITSINGH-he6uh 4 года назад

      just to check will this code loop through all the countries (as we are just selecting top 1 country in the internal query)

  • @djjiang3718
    @djjiang3718 3 года назад

    Venka is one of the best teachers on this planet!

  • @angelsabillon93
    @angelsabillon93 9 лет назад

    Hello, I would be very grateful if someone help me with this.
    How do I do to get a pivot table, from a table that is constantly updating its fields or having new ones?
    Not this:
    select * from Table
    pivot (max (Field) for IncomeDay in ([MON],[TUE],[WED],[THU],[FRI],[SAT],[SUN])) as MaxIncomePerDay
    where VendorId in ('ooo')
    but something like this:
    select *,("select of the updated query") from Table
    pivot (max (Field) for IncomeDay in ("here a select of the updated table") as MaxIncomePerDay
    where VendorId in ('ooo')

  • @ymtan
    @ymtan 10 лет назад +1

    Awesome Tutorial

  • @harishraj3912
    @harishraj3912 7 лет назад

    hi venkat , i have a doubt in this video, when you did transformation from rows to columns, isn't that the violation of 1NF. because imagine if UK has only one city LONDON then the columns City2 and City 3 will violate the 1NF right?

  • @borkasiamese4617
    @borkasiamese4617 10 лет назад

    Thank you!

  • @rupjitroy8244
    @rupjitroy8244 3 года назад +1

    Hi Venkat, the videos really made a difference while developing my skills. I will be forever grateful to this series. I faced few difficulties while using Pivot functionality in PostGRE so I came up with this alternative, can you let me know if this works?-
    with base as
    (
    select row_number() over (partition by country order by country) ran, country, city
    from countries
    )
    select a.country,a.City1, b.City2, c.City3 from
    (
    (select country, city as City1
    from
    base
    where ran = 1
    ) a
    join
    (select country, city as City2
    from
    base
    where ran = 2
    ) b
    on a.country=b.country
    join
    (select country, city as City3
    from
    base
    where ran = 3
    ) c
    on a.country=c.country
    )

  • @krishnamohankumar
    @krishnamohankumar 6 лет назад +1

    is it easier like below
    select
    country,
    max(case when rnk=1 then city end) over (partition by country) city_1,
    max(case when rnk=2 then city end) over (partition by country) city_2,
    max(case when rnk=3 then city end) over (partition by country) city_3
    FROM
    (
    select
    country,
    city,
    rank() over (partition by country order by city ) rnk
    FROM Countries
    ) abc

  • @mohammedalkhafaf4229
    @mohammedalkhafaf4229 8 лет назад +1

    thanks for useful information

  • @kumavatjayesh1267
    @kumavatjayesh1267 6 лет назад +15

    what happens when there are 1000 cities... considering this video will you right 1000 cities.. so please clear this doubt and make it dynamic and other things are good sir...

    • @allshort6436
      @allshort6436 2 года назад

      You have to make a stored procedure with declaration of 2 parameter ...for making it dynamic.

  • @KamilIbadov
    @KamilIbadov 10 лет назад

    Thanks you!

  • @krismaly6300
    @krismaly6300 10 лет назад

    This is another great video.
    Guruji,
    I think before select statement it's better to build a string (strCity) and use the string in that case we will never alter the statements for every data inserted with new city
    What do you think?
    Lots of thanks for teaching

  • @sunilkumarkashyap199
    @sunilkumarkashyap199 9 лет назад

    Hi, Venket!
    I have a scenario in which i have column like products, year, months and salesvalue in rupees.
    now i want to pivot the records on year + month
    but problem is that I have about 25 - 30 column and may be it could more than in future.
    can we get the column dynamically.
    Thanks in advance!
    Sunil Kumar Kashyap

  • @berinjeio7433
    @berinjeio7433 2 года назад

    Thank you sir , the way of explanation is very simple and clear very easy to understand.

  • @Tarikffm79
    @Tarikffm79 10 лет назад +8

    Thanks a Lot kudvenkat My question is their any other Way to make the fourth rows dynamic? Maybe sometimes you dont know how many rows you have! Best regards!

    • @adamstevens5518
      @adamstevens5518 6 лет назад +1

      If you don't know how many cities there are going to be, it should work to add City4, City5, City6, etc. to the Select statement and the ColumnSequence statement. It should then give NULL values if the country does not have that many cities.
      This worked for me in a modified version of this code that I used to pivot a bunch of vital sign readings from rows into columns, with one row for each unique person with readings.

    • @wildone2163
      @wildone2163 6 лет назад +2

      Exactly what I'd like to see, a dynamic solution for number of columns.

  • @MatthewWagnerNOECA
    @MatthewWagnerNOECA 4 года назад

    Great Video... Thanks!

  • @gopiputta6640
    @gopiputta6640 7 лет назад

    Hello venkat sir why i am not getting the table .
    select * from(select Store,Week,xCount from yt)src pivot(sum(xCount) for Week in ([1], [2], [3]))piv;
    why isn't working
    is there any software problem .it's showing like
    -> ;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mysql version' at line 1.

  • @gopiputta6640
    @gopiputta6640 7 лет назад

    Hi venkat sir these videos are very helpful.But how can i do transformation of rows into columns using stored procedures.It's urgent sir.

  • @amitkamble8493
    @amitkamble8493 Год назад

    first time I saw concatenation of row_number with string using cast for row_number. Awesome logic

  • @RP-nf7fl
    @RP-nf7fl 5 лет назад

    Hello Venkat, many of your videos in this series have blurry view , i can see other youtube videos fine but when i run yours in this series, it is blurry. Can you check that please?

  • @sapnaantara9031
    @sapnaantara9031 4 года назад

    Thank you so much for this video. It helped a lot

    • @Csharp-video-tutorialsBlogspot
      @Csharp-video-tutorialsBlogspot  4 года назад

      You are very welcome Sapna. I am very glad you are finding our courses useful. Thank you for the feedback. You can find our complete SQL course at the following link which I think could be useful as well.
      ruclips.net/p/PL08903FB7ACA1C2FB

  • @debabratatripathy3409
    @debabratatripathy3409 10 лет назад

    awesome video on pivot....thanks

  • @pankajnemade
    @pankajnemade 5 лет назад

    Very useful.... Thank you....

  • @saagarsoni3
    @saagarsoni3 10 лет назад

    thank u very much sir

  • @DOMINILOCO
    @DOMINILOCO 6 лет назад

    what if i have different tables joined how can I implement this?

  • @anirbande2009
    @anirbande2009 9 лет назад

    How to dynamically allocate column names?

  • @LEKGOTLAR
    @LEKGOTLAR 9 лет назад

    How can I do the opposite of what you did,I need to split ordersTransaction by products.(eg) If I have a single row that has this information
    [CustomerID]Customer102,[Product1]Burger,[Product2]OrangeJuice,[Product3]Fries
    =====================================
    Transaction 1,Customer102,Burger(Product1)
    Transaction 2,Customer102,OrangeJuice(Product2)
    Transaction 3,Customer102,Fries(Product3)
    =====================================

  • @sreekanthk9667
    @sreekanthk9667 5 лет назад

    If we don’t know the values in the column ,how can we do the same?

  • @ced4298
    @ced4298 2 года назад

    Great explanation and presentation voice

  • @mauroldanr
    @mauroldanr 7 лет назад

    excellent

  • @nikhilkadam4914
    @nikhilkadam4914 4 года назад

    HI Sir,
    If we don not know the how many rows to be convert in to columns for ex. we know in this example 4 columns are city but if don't know cities than how can we do

  • @kushagrak4903
    @kushagrak4903 3 года назад

    I'm trying to do this query in Mysql but unfortunately mysql doesn't have pivot function , so is there any alternative way to create pivots using mysql

  • @annachan5676
    @annachan5676 3 года назад

    is there a way to pivot multiple values, ex city AND zipcode?

  • @ashwathraj9882
    @ashwathraj9882 6 лет назад +2

    Can you pls explain why we are using max(city) for the aggregation ?

  • @laurendai1731
    @laurendai1731 7 лет назад

    why use MAX (city ) in Pivot part? thanks

  • @vixgma
    @vixgma 2 года назад

    Hi, what if the raw data has more than 2 columns (say 5 columns) and how to transpose it?

  • @minakshidas2587
    @minakshidas2587 7 лет назад

    Can you please explain how to convert rows into columns without using pivot function ?

  • @ashwinibandgar5566
    @ashwinibandgar5566 10 лет назад +2

    Thanks sir.Very useful videos.I have question asked in interview.In 1 table contains columns deptid,deptname and another table empid,empname and deptid which is foreign key of first tabel(column deptid).Question was display department which has maximum employees.Please help to write this query

    • @Csharp-video-tutorialsBlogspot
      @Csharp-video-tutorialsBlogspot  10 лет назад

      Hi Ashwini, very good question. Answering this question requires the knowledge of Joins and GroupBy. If you are new to those concepts, I recommend to watch Parts 11 & 12 from SQL Server Tutorial playlist. I will record and upload a video answering your question very soon. Thanks for asking. Good Luck.

  • @relyontestmail3171
    @relyontestmail3171 4 года назад

    thanks a lot guruji

  • @sourabhthorat9550
    @sourabhthorat9550 2 года назад

    Excellent

  • @johanefendy6082
    @johanefendy6082 8 лет назад +1

    Than's very useful worked for me

    • @Csharp-video-tutorialsBlogspot
      @Csharp-video-tutorialsBlogspot  8 лет назад +1

      Thank you very much for taking time to give feedback. This means a lot. I am very glad you found the videos useful.
      I have organised all the Dot Net & SQL Server videos in to playlists, which could be useful to you
      ruclips.net/user/kudvenkatplaylists?view=1&sort=dd
      If you need DVDs or to download all the videos for offline viewing please visit
      www.pragimtech.com/kudvenkat_dvd.aspx
      Slides and Text Version of the videos can be found on my blog
      csharp-video-tutorials.blogspot.com
      Tips to effectively use my youtube channel.
      ruclips.net/video/y780MwhY70s/видео.html
      If you want to receive email alerts, when new videos are uploaded, please subscribe to my youtube channel.
      ruclips.net/user/kudvenkat
      If you like these videos, please click on the THUMBS UP button below the video.
      May I ask you for a favor. I want these tutorials to be helpful for as many people as possible. Please share the link with your friends and family who you think would also benefit from them.
      Good Luck
      Venkat

    • @user-xm4ic6be5z
      @user-xm4ic6be5z 7 лет назад

      ɷ Heeyy Frienddssss I Have F0unddd W0rikinggggg Online Hacck visitt : - t.co/lwCJIlgsKa

  • @godofroot9216
    @godofroot9216 4 года назад +1

    And What we do when we have unkown number of cities? Please it's urgent.

    • @AJITSINGH-he6uh
      @AJITSINGH-he6uh 4 года назад

      Have you got the answer, if yes, pls share.

  • @BinhLe-wg3ym
    @BinhLe-wg3ym 4 года назад

    Thanks

  • @untoldbharat07
    @untoldbharat07 7 лет назад

    Nice Video.............

  • @BoringYTBR
    @BoringYTBR 6 лет назад

    For dynamic numbers using stuff function
    DECLARE @CITY VARCHAR(500) = STUFF(
    (SELECT distinct ', ' + 'City' + cast(row_number() over(partition by Country order by Country) as varchar(10))
    FROM Countries FOR XML PATH('')
    ),1,1,''
    )
    --SELECT @CITY
    declare @DynamicPivotQuery nvarchar(max)
    set @DynamicPivotQuery=
    'Select Country, '+@CITY+'
    From
    (
    Select Country, City,
    ''City''+
    cast(row_number() over(partition by Country order by Country)
    as varchar(10)) ColumnSequence
    from Countries
    ) Temp
    pivot
    (
    max(City)
    for ColumnSequence in ('+@CITY+')
    ) Piv'

  • @dreambig9794
    @dreambig9794 2 года назад

    Hi, Thank for this video, but after applying same logic I am not getting data in one row. It's coming in multiple rows with null and transpose data is not is single row.

  • @upendrakumarpandey2838
    @upendrakumarpandey2838 7 лет назад

    really nice video please sir post a dynamic pivot

  • @skabdulrahim4318
    @skabdulrahim4318 3 года назад

    Thank you so mush for this video,
    Sir can we achieve pivot result dynamically...?

  • @madhulikasuman2803
    @madhulikasuman2803 2 года назад

    the above code is nt going to work if there is city4,5 etc...any code need to be dynamic

  • @Indian_working_mom
    @Indian_working_mom 4 года назад +1

    Sir it is not working in SQL

  • @nitujaiswal5617
    @nitujaiswal5617 8 лет назад +1

    You are really amazing in teaching, I ever seen.
    Could you please help me for this example :
    CREATE TABLE OIVOT
    (
    COL1 INT,
    COL2 NVARCHAR(20),
    COL3 NVARCHAR(20),
    )
    INSERT INTO OIVOT VALUES (1,'TOM','HAPPY'),(1,'TIM','GOOD'),(2,'JACK','SAD'),(3,'JOHN','ANGRY'),(3,'JOHNY','HAPPY')

  • @RexIDevil
    @RexIDevil 7 лет назад

    sir if have new delhi twice what will happen

    • @gshrdy5415
      @gshrdy5415 6 лет назад

      write a querry to delete duplicates then pivot.

  • @beunique4822
    @beunique4822 2 года назад

    sir y max is used ? max(city)?

  • @ShamsherSingh-rf5hk
    @ShamsherSingh-rf5hk 5 лет назад

    Sir showing error near as

  • @raghavendrag6899
    @raghavendrag6899 5 лет назад

    Please tell me how to write query below?
    Output column is calculated with adding Amt1 and Amt2 values to the Output Column value of previous record.
    Example: Output Column of
    first record is as it is of Amount column,
    second record will get from first record value of output column and amt1 , amt2 of first record i.e 100+0+10=110,
    third record is from 110+10+0=120
    fourth record is from 120+0+0=120
    fifth record is from 120+300+10=430 ...
    Input:
    dated amount amt1 amt2
    1/1/2017 100 0 10
    1/2/2017 100 10 0
    1/4/2017 100 0 0
    1/6/2017 100 300 10
    1/10/2017 100 0 20
    1/11/2017 100 350 650
    1/12/2017 100 0 234
    Output:
    dated amount amt1 amt2 Output Column
    1/1/2017 100 0 10 100
    1/2/2017 100 10 0 110
    1/4/2017 100 0 0 120
    1/6/2017 100 300 10 120
    1/10/2017 100 0 20 430
    1/11/2017 100 350 650 450
    1/12/2017 100 0 234 1450
    how to write query

  • @shaharukhpathan5331
    @shaharukhpathan5331 6 лет назад

    Questions: Create Normalize Structure Database of Job seeker Website With 3 Table Containing job_Seeker,Job_Seeker_Skill,Job_Seeker_Address Note that job Seeker Can Have Multiple Skill Set... Thanks In Advance