Dynamically Pivot Data in SQL Server

Поделиться
HTML-код
  • Опубликовано: 3 авг 2018
  • In this video we will write T-SQL in SQL Server to build a dynamic query that will pivot a data set.
    Watch the video and get the code here: anthonysmoak.com/2018/08/05/h...
    ★☆★ Join this channel to get access to perks: ★☆★
    / @anthonysmoak
    ★☆★ SUPPORT THIS CHANNEL: ★☆★
    shop.spreadshirt.com/AnthonyS...
    ★☆★ FOLLOW ME BELOW: ★☆★
    Blog ► anthonysmoak.com/​
    Twitter ► / anthonysmoak​
    Facebook ► / ​
    Tableau Public ► public.tableau.com/profile/an...
    #SQL #SQLServer #data​ #analytics​ #data​ #dataanalyst​ #education​ #onlinelearning

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

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

    Great contents and examples, Loved it

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

    Great job explaining PIVOT function, you were easy to listen to and understand

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

    Super helpful and much appreciated.

  • @rickvenables7648
    @rickvenables7648 Год назад +1

    This was a tremendous help to get my similar query to work. Thanks much!

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

      Glad to hear it! Thanks for the comment.

  • @Coder-zx4nb
    @Coder-zx4nb 5 лет назад +1

    Awesome video. Helped me get a clear grasp on pivots.

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

    thank you very much! you really helped me.

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

    thank you this helped me a lot :)

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

    really so best explanation😊😊

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

    Thanks for the video. Very enlightening.

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

    Hi Anthony, I have a quick questions, how would you modify this query for a different scenario if there are two fields that needs to be filled in the Pivot for a single city, so for example let us assume 6118 and 6181 both should have rents assigned to sanfrancisco, if you see in your scenario no one city has got more than one rent filled in its rows

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

    Really good video thanks for posting

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

      Thanks for watching and commenting.

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

    This was so useful, damn I was just told that I would be using this for taking data from certain tables and so on so this is soo so handy, thank you so much

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

      Fantastic! I enjoy hearing how my channel helps people with their data. Thanks for commenting!

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

    Awesome..

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

    OK, how can I use the Distinct in between city and QUOTENAME

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

    best pivot example on youtube

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

      Thank you, I'm glad I was able to help!

  • @farahfarooq3755
    @farahfarooq3755 4 года назад +2

    Amazing example for new bies

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

    you are king, thank you..

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

      My subscribers are royalty. Thanks for watching!

  • @KhanStyle380
    @KhanStyle380 Год назад +1

    You saved my days…. Thanks

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

    How can I put two columns in Pivot?

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

    Is it possible to create a view that contains the resultset?

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

    I think a better dataset would have lead to a clearer "pivot table", I understand where/why the NULL's are coming, however not everyone might understand how a different dataset would have been more interesting (such as demographics by city, county state). That said you did a great job explaining the how/why of the SQL.

  • @prashantrawat5466
    @prashantrawat5466 Год назад +1

    Niceeeeee

  • @edwin60590
    @edwin60590 2 года назад +1

    Solved my curiosity, thx

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

      Glad to hear it, thanks for the comment!

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

    Hey Anthony, great job in explaining the pivot function. I have a question to ask, it would be great if you could reply - How can we handle a scenario where the 'city' column would have more than 10,000 unique cities (let's assume) ?

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

      well I mean, if it needs to be readable I'd use another reference like country or so. Maybe try to orient the query to a specific type of data like above certain numer?

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

    hello Sir I had a problem can you help me

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

    Cashville!

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

    Thank you!
    Here, I don't want to display 'NULL' or '0' in the result, so that we can view a clear picture of the output. Can you please provide the query for it?

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

      Try using the COALESCE function in a CASE statement to turn your NULL and 0 values into the empty string ''.

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

      Or just use the Isnull function

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

    Please post table and data

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

    hi there lovely video however i am having a problem, by your method i am able to get the columns dynamically but problem is they are not unique and repeating value, just like it has combine all the row data in one cell, can you help out on this

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

      It's difficult to diagnose with limited information. Some tweaking to the code may be warranted based upon your specific data set.

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

      If you first Select Distinct on the column you are going to pivot and store it in a temp table IE #ColumnNames You can then use that in place of the (Cities) column in the pivot and you will get unique columns.

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

      @@beadww Bradley could you show an example of this please

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

    it is showing an error
    Msg 8156, Level 16, State 1, Line 6
    The column 'Feb 1 2018 12:00AM' was specified multiple times for 'Q'.
    Msg 208, Level 16, State 0, Line 34
    Invalid object name '##TBL_TEMP1'.

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

    hello
    I know it's been a long time ...
    it is possible to leave all the data on the left ... I have a purpose to do it.
    thanks for sharing

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

      You want to exclude certain fields? If so, simply select what you need from the temp table that holds the pivot results.

  • @SandeepTiwari-yy4fg
    @SandeepTiwari-yy4fg Год назад +1

    how to make zero(0) if Average rent is null or how to use ISNULL function here

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

      Check out the COALESCE() function.

    • @SandeepTiwari-yy4fg
      @SandeepTiwari-yy4fg Год назад

      @@AnthonySmoak sir this is my code SET @query = '
      SELECT *
      INTO #TempPivot
      FROM (
      SELECT DepartmentCode, '+ @cols+ '
      FROM (
      SELECT DepartmentCode, Label, isnull(Amount, 0) AS Amount
      FROM #temp
      UNION ALL
      SELECT ''Total'', Label, SUM(Amount)
      FROM #temp
      GROUP BY Label
      ) AS ResultTable
      PIVOT (
      SUM(Amount)
      FOR Label IN (' + @cols + ')
      ) AS PivotTable
      ) AS FinalResult;
      -- Select from the temporary table
      SELECT * FROM #TempPivot;
      -- Drop the temporary table
      DROP TABLE IF EXISTS #TempPivot;';
      -- Execute the dynamic SQL query
      EXEC sp_executesql @query;
      but it gives this error
      Incorrect syntax near the keyword 'COALESCE'.
      pls can you help on this.

    • @SandeepTiwari-yy4fg
      @SandeepTiwari-yy4fg Год назад

      DECLARE @cols AS NVARCHAR(MAX);
      DECLARE @query AS NVARCHAR(MAX);
      -- Get the distinct label values dynamically
      SET @cols = STUFF(
      (
      SELECT DISTINCT ', COALESCE(' + QUOTENAME(Label) + ', 0) AS ' + QUOTENAME(Label)
      FROM #temp
      FOR XML PATH(''), TYPE
      ).value('.', 'NVARCHAR(MAX)'),
      1, 2, ''
      );
      sorry code this I missed

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

    I need to run this in C#.. How can I do it?

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

      Not sure about that one. That is out of my lane.

  • @davidmumford367
    @davidmumford367 5 месяцев назад

    where did tbl_rent come from

    • @AnthonySmoak
      @AnthonySmoak  5 месяцев назад

      World bank dataset, found it over 5 years ago somewhere.

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

    How do we do the same Dynamic Pivot in SSIS...?

    • @AnthonySmoak
      @AnthonySmoak  Год назад +1

      Use the Execute SQL task: learn.microsoft.com/en-us/sql/integration-services/control-flow/execute-sql-task?view=sql-server-ver16

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

      @@AnthonySmoak My source is Excel and the destination is OLE-DB...is it possible to Execute the SQL task.

    • @AnthonySmoak
      @AnthonySmoak  Год назад +1

      If your data is in Excel, in order for SQL to work, you would need to import it into a relational database first. Excel is not a relational database. However, you can use the unpivot functionality in Power Query to get the same results as the SQL in this video. anthonysmoak.com/2017/07/16/easily-unpivot-your-data-in-excel-using-power-query/

    • @mathiyarasuelangovan2694
      @mathiyarasuelangovan2694 Год назад +1

      @@AnthonySmoak Thank You ...

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

      @@mathiyarasuelangovan2694 Good luck!

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

    How to handle that null value and replace as 0????

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

    What if city is repeated?

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

      Then you would have a data quality issue with respect to this example.

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

      @@AnthonySmoak okay

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

    omg even on a lot of rows, you can still make pivot table like this in excel with exactly 2 cliks…………..

    • @AnthonySmoak
      @AnthonySmoak  4 года назад +7

      Sure, but try doing this in Excel with 10 million rows. :)

  • @thomasbates804
    @thomasbates804 Год назад +1

    This is very helpful. Thank you