How do I prevent NULL fields in rows SQL Pivot?












0














I am running a SQL Pivot against varchar.



I have the following table:




`Continent | State | City
---------------------------------------------
North America | California | Oakland
North America | California | Los Angeles
North America | California | Sacramento
North America | California | San Diego
North America | California | San Francisco
North America | California | Upton
North America | Florida | Jacksonville
North America | Florida | Fort Lauderdale
North America | Florida | Miami
North America | Florida | Tampa
North America | New York | Albany
North America | New York | Buffalo
North America | New York | New York
North America | New York | Rochester
North America | New York | Utica
North America | Texas | Austin
North America | Texas | Dallas
North America | Texas | San Antonio`


and I want to create a pivot table that looks like this:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | Albany | Austin
North America | Los Angeles | Fort Lauderdale | Buffalo | Dallas
North America | Sacramento | Miami | New York | San Antonio
North America | San Diego | Tampa | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


I am currently using the following code:





` SELECT *
FROM
(
SELECT Placename.Continent,
Placename.State,
Placename.City,
row_number() over(partition by Placename.State order by Placename.City) rn
FROM Placename
) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
[Florida],
[New York],
[Texas]
)) AS PivotTable`


Note: Min(City) and Max(City) gave me the same output



Now, after using this code, the following table is given:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | NULL | Austin
North America | NULL | Fort Lauderdale | Albany | Dallas
North America | Los Angeles | NULL | Buffalo | NULL
North America | Sacramento | Miami | New York | San Antonio
North America | NULL | Tampa | NULL | NULL
North America | San Diego | NULL | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


What is the reason that the table being output is not the same as the desired table output?










share|improve this question
























  • removing row_number now only selects the first city in each state, not all cities from each state
    – Blitz
    Nov 8 at 4:12












  • you wanted all or first city of each state ?
    – Squirrel
    Nov 8 at 4:29










  • all of each state
    – Blitz
    Nov 8 at 4:55






  • 1




    It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
    – scratt
    Nov 8 at 5:03






  • 1




    I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
    – Dale Burrell
    Nov 8 at 5:12
















0














I am running a SQL Pivot against varchar.



I have the following table:




`Continent | State | City
---------------------------------------------
North America | California | Oakland
North America | California | Los Angeles
North America | California | Sacramento
North America | California | San Diego
North America | California | San Francisco
North America | California | Upton
North America | Florida | Jacksonville
North America | Florida | Fort Lauderdale
North America | Florida | Miami
North America | Florida | Tampa
North America | New York | Albany
North America | New York | Buffalo
North America | New York | New York
North America | New York | Rochester
North America | New York | Utica
North America | Texas | Austin
North America | Texas | Dallas
North America | Texas | San Antonio`


and I want to create a pivot table that looks like this:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | Albany | Austin
North America | Los Angeles | Fort Lauderdale | Buffalo | Dallas
North America | Sacramento | Miami | New York | San Antonio
North America | San Diego | Tampa | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


I am currently using the following code:





` SELECT *
FROM
(
SELECT Placename.Continent,
Placename.State,
Placename.City,
row_number() over(partition by Placename.State order by Placename.City) rn
FROM Placename
) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
[Florida],
[New York],
[Texas]
)) AS PivotTable`


Note: Min(City) and Max(City) gave me the same output



Now, after using this code, the following table is given:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | NULL | Austin
North America | NULL | Fort Lauderdale | Albany | Dallas
North America | Los Angeles | NULL | Buffalo | NULL
North America | Sacramento | Miami | New York | San Antonio
North America | NULL | Tampa | NULL | NULL
North America | San Diego | NULL | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


What is the reason that the table being output is not the same as the desired table output?










share|improve this question
























  • removing row_number now only selects the first city in each state, not all cities from each state
    – Blitz
    Nov 8 at 4:12












  • you wanted all or first city of each state ?
    – Squirrel
    Nov 8 at 4:29










  • all of each state
    – Blitz
    Nov 8 at 4:55






  • 1




    It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
    – scratt
    Nov 8 at 5:03






  • 1




    I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
    – Dale Burrell
    Nov 8 at 5:12














0












0








0







I am running a SQL Pivot against varchar.



I have the following table:




`Continent | State | City
---------------------------------------------
North America | California | Oakland
North America | California | Los Angeles
North America | California | Sacramento
North America | California | San Diego
North America | California | San Francisco
North America | California | Upton
North America | Florida | Jacksonville
North America | Florida | Fort Lauderdale
North America | Florida | Miami
North America | Florida | Tampa
North America | New York | Albany
North America | New York | Buffalo
North America | New York | New York
North America | New York | Rochester
North America | New York | Utica
North America | Texas | Austin
North America | Texas | Dallas
North America | Texas | San Antonio`


and I want to create a pivot table that looks like this:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | Albany | Austin
North America | Los Angeles | Fort Lauderdale | Buffalo | Dallas
North America | Sacramento | Miami | New York | San Antonio
North America | San Diego | Tampa | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


I am currently using the following code:





` SELECT *
FROM
(
SELECT Placename.Continent,
Placename.State,
Placename.City,
row_number() over(partition by Placename.State order by Placename.City) rn
FROM Placename
) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
[Florida],
[New York],
[Texas]
)) AS PivotTable`


Note: Min(City) and Max(City) gave me the same output



Now, after using this code, the following table is given:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | NULL | Austin
North America | NULL | Fort Lauderdale | Albany | Dallas
North America | Los Angeles | NULL | Buffalo | NULL
North America | Sacramento | Miami | New York | San Antonio
North America | NULL | Tampa | NULL | NULL
North America | San Diego | NULL | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


What is the reason that the table being output is not the same as the desired table output?










share|improve this question















I am running a SQL Pivot against varchar.



I have the following table:




`Continent | State | City
---------------------------------------------
North America | California | Oakland
North America | California | Los Angeles
North America | California | Sacramento
North America | California | San Diego
North America | California | San Francisco
North America | California | Upton
North America | Florida | Jacksonville
North America | Florida | Fort Lauderdale
North America | Florida | Miami
North America | Florida | Tampa
North America | New York | Albany
North America | New York | Buffalo
North America | New York | New York
North America | New York | Rochester
North America | New York | Utica
North America | Texas | Austin
North America | Texas | Dallas
North America | Texas | San Antonio`


and I want to create a pivot table that looks like this:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | Albany | Austin
North America | Los Angeles | Fort Lauderdale | Buffalo | Dallas
North America | Sacramento | Miami | New York | San Antonio
North America | San Diego | Tampa | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


I am currently using the following code:





` SELECT *
FROM
(
SELECT Placename.Continent,
Placename.State,
Placename.City,
row_number() over(partition by Placename.State order by Placename.City) rn
FROM Placename
) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
[Florida],
[New York],
[Texas]
)) AS PivotTable`


Note: Min(City) and Max(City) gave me the same output



Now, after using this code, the following table is given:




`Continent | California | Florida | New York | Texas
-----------------------------------------------------------------------
North America | Oakland | Jacksonville | NULL | Austin
North America | NULL | Fort Lauderdale | Albany | Dallas
North America | Los Angeles | NULL | Buffalo | NULL
North America | Sacramento | Miami | New York | San Antonio
North America | NULL | Tampa | NULL | NULL
North America | San Diego | NULL | Rochester | NULL
North America | San Francisco | NULL | Utica | NULL
North America | Upton | NULL | NULL | NULL`


What is the reason that the table being output is not the same as the desired table output?







sql sql-server tsql database-design pivot






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 4:04

























asked Nov 8 at 3:57









Blitz

11




11












  • removing row_number now only selects the first city in each state, not all cities from each state
    – Blitz
    Nov 8 at 4:12












  • you wanted all or first city of each state ?
    – Squirrel
    Nov 8 at 4:29










  • all of each state
    – Blitz
    Nov 8 at 4:55






  • 1




    It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
    – scratt
    Nov 8 at 5:03






  • 1




    I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
    – Dale Burrell
    Nov 8 at 5:12


















  • removing row_number now only selects the first city in each state, not all cities from each state
    – Blitz
    Nov 8 at 4:12












  • you wanted all or first city of each state ?
    – Squirrel
    Nov 8 at 4:29










  • all of each state
    – Blitz
    Nov 8 at 4:55






  • 1




    It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
    – scratt
    Nov 8 at 5:03






  • 1




    I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
    – Dale Burrell
    Nov 8 at 5:12
















removing row_number now only selects the first city in each state, not all cities from each state
– Blitz
Nov 8 at 4:12






removing row_number now only selects the first city in each state, not all cities from each state
– Blitz
Nov 8 at 4:12














you wanted all or first city of each state ?
– Squirrel
Nov 8 at 4:29




you wanted all or first city of each state ?
– Squirrel
Nov 8 at 4:29












all of each state
– Blitz
Nov 8 at 4:55




all of each state
– Blitz
Nov 8 at 4:55




1




1




It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
– scratt
Nov 8 at 5:03




It might be more helpful if you showed the full results of the query, especially the rn column. Your query seems to be correct, but we might learn more seeing the results. Of course if you provide the scripts necessary to populate tables with your dataset, that would help even more. Please see this article to get started: stackoverflow.com/help/how-to-ask
– scratt
Nov 8 at 5:03




1




1




I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
– Dale Burrell
Nov 8 at 5:12




I just ran your exact query with your exact data, and it gave me your desired output - not your supposed actual output. So there must be more to this than posted.
– Dale Burrell
Nov 8 at 5:12












2 Answers
2






active

oldest

votes


















2














just try this:



DECLARE @tbl TABLE(Continent VARCHAR(100),[State] VARCHAR(100),City VARCHAR(100));
INSERT INTO @tbl VALUES
('North America','California','Oakland')
,('North America','California','Los Angeles')
,('North America','California','Sacramento')
,('North America','California','San Diego')
,('North America','California','San Francisco')
,('North America','California','Upton')
,('North America','Florida','Jacksonville')
,('North America','Florida','Fort Lauderdale')
,('North America','Florida','Miami')
,('North America','Florida','Tampa')
,('North America','New York','Albany')
,('North America','New York','Buffalo')
,('North America','New York','New York')
,('North America','New York','Rochester')
,('North America','New York','Utica')
,('North America','Texas','Austin')
,('North America','Texas','Dallas')
,('North America','Texas','San Antonio');

SELECT *
FROM
(
SELECT Placename.Continent,
Placename.State,
Placename.City,
row_number() over(partition by Placename.State order by Placename.City) rn
FROM @tbl AS PlaceName
) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
[Florida],
[New York],
[Texas]
)) AS PivotTable;


This is exactly your own query working against a mockup-table. As far as I see, the result is exactly the one you need:



+---------------+----+---------------+-----------------+-----------+-------------+
| Continent | rn | California | Florida | New York | Texas |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 1 | Los Angeles | Fort Lauderdale | Albany | Austin |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 2 | Oakland | Jacksonville | Buffalo | Dallas |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 3 | Sacramento | Miami | New York | San Antonio |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 4 | San Diego | Tampa | Rochester | NULL |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 5 | San Francisco | NULL | Utica | NULL |
+---------------+----+---------------+-----------------+-----------+-------------+
| North America | 6 | Upton | NULL | NULL | NULL |
+---------------+----+---------------+-----------------+-----------+-------------+


If there is more behind, please use my stand-alone sample from above, set up a running example like mine and describe what else you'd need.






share|improve this answer





























    0














    Something like this should do it for you.



    --DROP TABLE #C
    CREATE TABLE #C (X CHAR(1) , ID INT)
    INSERT INTO #C values('A', 1)
    INSERT INTO #C values(NULL, 2)
    INSERT INTO #C values('B', 3)
    INSERT INTO #C values('C', 4)
    INSERT INTO #C values(NULL, 5)
    INSERT INTO #C values('D', 6)

    select *
    from #C


    enter image description here



    SELECT ID,CASE WHEN X is not null
    THEN X
    ELSE (SELECT max(X)
    FROM #C
    WHERE ID <= t.ID)
    END AS X
    FROM #C t


    enter image description here



    If its sql 2012 use this



    SELECT ID,
    COALESCE(Name,
    LAG(Name,1) OVER (ORDER BY ID )) AS Name
    FROM Table
    If there can be multiple gaps use this instead
    SELECT ID,
    COALESCE(Name,
    MAX(COALESCE(Name,'')) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS Name
    FROM Table





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53201351%2fhow-do-i-prevent-null-fields-in-rows-sql-pivot%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      just try this:



      DECLARE @tbl TABLE(Continent VARCHAR(100),[State] VARCHAR(100),City VARCHAR(100));
      INSERT INTO @tbl VALUES
      ('North America','California','Oakland')
      ,('North America','California','Los Angeles')
      ,('North America','California','Sacramento')
      ,('North America','California','San Diego')
      ,('North America','California','San Francisco')
      ,('North America','California','Upton')
      ,('North America','Florida','Jacksonville')
      ,('North America','Florida','Fort Lauderdale')
      ,('North America','Florida','Miami')
      ,('North America','Florida','Tampa')
      ,('North America','New York','Albany')
      ,('North America','New York','Buffalo')
      ,('North America','New York','New York')
      ,('North America','New York','Rochester')
      ,('North America','New York','Utica')
      ,('North America','Texas','Austin')
      ,('North America','Texas','Dallas')
      ,('North America','Texas','San Antonio');

      SELECT *
      FROM
      (
      SELECT Placename.Continent,
      Placename.State,
      Placename.City,
      row_number() over(partition by Placename.State order by Placename.City) rn
      FROM @tbl AS PlaceName
      ) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
      [Florida],
      [New York],
      [Texas]
      )) AS PivotTable;


      This is exactly your own query working against a mockup-table. As far as I see, the result is exactly the one you need:



      +---------------+----+---------------+-----------------+-----------+-------------+
      | Continent | rn | California | Florida | New York | Texas |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 1 | Los Angeles | Fort Lauderdale | Albany | Austin |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 2 | Oakland | Jacksonville | Buffalo | Dallas |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 3 | Sacramento | Miami | New York | San Antonio |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 4 | San Diego | Tampa | Rochester | NULL |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 5 | San Francisco | NULL | Utica | NULL |
      +---------------+----+---------------+-----------------+-----------+-------------+
      | North America | 6 | Upton | NULL | NULL | NULL |
      +---------------+----+---------------+-----------------+-----------+-------------+


      If there is more behind, please use my stand-alone sample from above, set up a running example like mine and describe what else you'd need.






      share|improve this answer


























        2














        just try this:



        DECLARE @tbl TABLE(Continent VARCHAR(100),[State] VARCHAR(100),City VARCHAR(100));
        INSERT INTO @tbl VALUES
        ('North America','California','Oakland')
        ,('North America','California','Los Angeles')
        ,('North America','California','Sacramento')
        ,('North America','California','San Diego')
        ,('North America','California','San Francisco')
        ,('North America','California','Upton')
        ,('North America','Florida','Jacksonville')
        ,('North America','Florida','Fort Lauderdale')
        ,('North America','Florida','Miami')
        ,('North America','Florida','Tampa')
        ,('North America','New York','Albany')
        ,('North America','New York','Buffalo')
        ,('North America','New York','New York')
        ,('North America','New York','Rochester')
        ,('North America','New York','Utica')
        ,('North America','Texas','Austin')
        ,('North America','Texas','Dallas')
        ,('North America','Texas','San Antonio');

        SELECT *
        FROM
        (
        SELECT Placename.Continent,
        Placename.State,
        Placename.City,
        row_number() over(partition by Placename.State order by Placename.City) rn
        FROM @tbl AS PlaceName
        ) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
        [Florida],
        [New York],
        [Texas]
        )) AS PivotTable;


        This is exactly your own query working against a mockup-table. As far as I see, the result is exactly the one you need:



        +---------------+----+---------------+-----------------+-----------+-------------+
        | Continent | rn | California | Florida | New York | Texas |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 1 | Los Angeles | Fort Lauderdale | Albany | Austin |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 2 | Oakland | Jacksonville | Buffalo | Dallas |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 3 | Sacramento | Miami | New York | San Antonio |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 4 | San Diego | Tampa | Rochester | NULL |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 5 | San Francisco | NULL | Utica | NULL |
        +---------------+----+---------------+-----------------+-----------+-------------+
        | North America | 6 | Upton | NULL | NULL | NULL |
        +---------------+----+---------------+-----------------+-----------+-------------+


        If there is more behind, please use my stand-alone sample from above, set up a running example like mine and describe what else you'd need.






        share|improve this answer
























          2












          2








          2






          just try this:



          DECLARE @tbl TABLE(Continent VARCHAR(100),[State] VARCHAR(100),City VARCHAR(100));
          INSERT INTO @tbl VALUES
          ('North America','California','Oakland')
          ,('North America','California','Los Angeles')
          ,('North America','California','Sacramento')
          ,('North America','California','San Diego')
          ,('North America','California','San Francisco')
          ,('North America','California','Upton')
          ,('North America','Florida','Jacksonville')
          ,('North America','Florida','Fort Lauderdale')
          ,('North America','Florida','Miami')
          ,('North America','Florida','Tampa')
          ,('North America','New York','Albany')
          ,('North America','New York','Buffalo')
          ,('North America','New York','New York')
          ,('North America','New York','Rochester')
          ,('North America','New York','Utica')
          ,('North America','Texas','Austin')
          ,('North America','Texas','Dallas')
          ,('North America','Texas','San Antonio');

          SELECT *
          FROM
          (
          SELECT Placename.Continent,
          Placename.State,
          Placename.City,
          row_number() over(partition by Placename.State order by Placename.City) rn
          FROM @tbl AS PlaceName
          ) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
          [Florida],
          [New York],
          [Texas]
          )) AS PivotTable;


          This is exactly your own query working against a mockup-table. As far as I see, the result is exactly the one you need:



          +---------------+----+---------------+-----------------+-----------+-------------+
          | Continent | rn | California | Florida | New York | Texas |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 1 | Los Angeles | Fort Lauderdale | Albany | Austin |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 2 | Oakland | Jacksonville | Buffalo | Dallas |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 3 | Sacramento | Miami | New York | San Antonio |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 4 | San Diego | Tampa | Rochester | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 5 | San Francisco | NULL | Utica | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 6 | Upton | NULL | NULL | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+


          If there is more behind, please use my stand-alone sample from above, set up a running example like mine and describe what else you'd need.






          share|improve this answer












          just try this:



          DECLARE @tbl TABLE(Continent VARCHAR(100),[State] VARCHAR(100),City VARCHAR(100));
          INSERT INTO @tbl VALUES
          ('North America','California','Oakland')
          ,('North America','California','Los Angeles')
          ,('North America','California','Sacramento')
          ,('North America','California','San Diego')
          ,('North America','California','San Francisco')
          ,('North America','California','Upton')
          ,('North America','Florida','Jacksonville')
          ,('North America','Florida','Fort Lauderdale')
          ,('North America','Florida','Miami')
          ,('North America','Florida','Tampa')
          ,('North America','New York','Albany')
          ,('North America','New York','Buffalo')
          ,('North America','New York','New York')
          ,('North America','New York','Rochester')
          ,('North America','New York','Utica')
          ,('North America','Texas','Austin')
          ,('North America','Texas','Dallas')
          ,('North America','Texas','San Antonio');

          SELECT *
          FROM
          (
          SELECT Placename.Continent,
          Placename.State,
          Placename.City,
          row_number() over(partition by Placename.State order by Placename.City) rn
          FROM @tbl AS PlaceName
          ) AS SourceTable PIVOT(Min(City) FOR [State] IN([California],
          [Florida],
          [New York],
          [Texas]
          )) AS PivotTable;


          This is exactly your own query working against a mockup-table. As far as I see, the result is exactly the one you need:



          +---------------+----+---------------+-----------------+-----------+-------------+
          | Continent | rn | California | Florida | New York | Texas |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 1 | Los Angeles | Fort Lauderdale | Albany | Austin |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 2 | Oakland | Jacksonville | Buffalo | Dallas |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 3 | Sacramento | Miami | New York | San Antonio |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 4 | San Diego | Tampa | Rochester | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 5 | San Francisco | NULL | Utica | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+
          | North America | 6 | Upton | NULL | NULL | NULL |
          +---------------+----+---------------+-----------------+-----------+-------------+


          If there is more behind, please use my stand-alone sample from above, set up a running example like mine and describe what else you'd need.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 8 at 7:22









          Shnugo

          48.5k72566




          48.5k72566

























              0














              Something like this should do it for you.



              --DROP TABLE #C
              CREATE TABLE #C (X CHAR(1) , ID INT)
              INSERT INTO #C values('A', 1)
              INSERT INTO #C values(NULL, 2)
              INSERT INTO #C values('B', 3)
              INSERT INTO #C values('C', 4)
              INSERT INTO #C values(NULL, 5)
              INSERT INTO #C values('D', 6)

              select *
              from #C


              enter image description here



              SELECT ID,CASE WHEN X is not null
              THEN X
              ELSE (SELECT max(X)
              FROM #C
              WHERE ID <= t.ID)
              END AS X
              FROM #C t


              enter image description here



              If its sql 2012 use this



              SELECT ID,
              COALESCE(Name,
              LAG(Name,1) OVER (ORDER BY ID )) AS Name
              FROM Table
              If there can be multiple gaps use this instead
              SELECT ID,
              COALESCE(Name,
              MAX(COALESCE(Name,'')) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS Name
              FROM Table





              share|improve this answer




























                0














                Something like this should do it for you.



                --DROP TABLE #C
                CREATE TABLE #C (X CHAR(1) , ID INT)
                INSERT INTO #C values('A', 1)
                INSERT INTO #C values(NULL, 2)
                INSERT INTO #C values('B', 3)
                INSERT INTO #C values('C', 4)
                INSERT INTO #C values(NULL, 5)
                INSERT INTO #C values('D', 6)

                select *
                from #C


                enter image description here



                SELECT ID,CASE WHEN X is not null
                THEN X
                ELSE (SELECT max(X)
                FROM #C
                WHERE ID <= t.ID)
                END AS X
                FROM #C t


                enter image description here



                If its sql 2012 use this



                SELECT ID,
                COALESCE(Name,
                LAG(Name,1) OVER (ORDER BY ID )) AS Name
                FROM Table
                If there can be multiple gaps use this instead
                SELECT ID,
                COALESCE(Name,
                MAX(COALESCE(Name,'')) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS Name
                FROM Table





                share|improve this answer


























                  0












                  0








                  0






                  Something like this should do it for you.



                  --DROP TABLE #C
                  CREATE TABLE #C (X CHAR(1) , ID INT)
                  INSERT INTO #C values('A', 1)
                  INSERT INTO #C values(NULL, 2)
                  INSERT INTO #C values('B', 3)
                  INSERT INTO #C values('C', 4)
                  INSERT INTO #C values(NULL, 5)
                  INSERT INTO #C values('D', 6)

                  select *
                  from #C


                  enter image description here



                  SELECT ID,CASE WHEN X is not null
                  THEN X
                  ELSE (SELECT max(X)
                  FROM #C
                  WHERE ID <= t.ID)
                  END AS X
                  FROM #C t


                  enter image description here



                  If its sql 2012 use this



                  SELECT ID,
                  COALESCE(Name,
                  LAG(Name,1) OVER (ORDER BY ID )) AS Name
                  FROM Table
                  If there can be multiple gaps use this instead
                  SELECT ID,
                  COALESCE(Name,
                  MAX(COALESCE(Name,'')) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS Name
                  FROM Table





                  share|improve this answer














                  Something like this should do it for you.



                  --DROP TABLE #C
                  CREATE TABLE #C (X CHAR(1) , ID INT)
                  INSERT INTO #C values('A', 1)
                  INSERT INTO #C values(NULL, 2)
                  INSERT INTO #C values('B', 3)
                  INSERT INTO #C values('C', 4)
                  INSERT INTO #C values(NULL, 5)
                  INSERT INTO #C values('D', 6)

                  select *
                  from #C


                  enter image description here



                  SELECT ID,CASE WHEN X is not null
                  THEN X
                  ELSE (SELECT max(X)
                  FROM #C
                  WHERE ID <= t.ID)
                  END AS X
                  FROM #C t


                  enter image description here



                  If its sql 2012 use this



                  SELECT ID,
                  COALESCE(Name,
                  LAG(Name,1) OVER (ORDER BY ID )) AS Name
                  FROM Table
                  If there can be multiple gaps use this instead
                  SELECT ID,
                  COALESCE(Name,
                  MAX(COALESCE(Name,'')) OVER (ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)) AS Name
                  FROM Table






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 20 at 3:05

























                  answered Nov 20 at 2:51









                  ryguy72

                  3,9451619




                  3,9451619






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53201351%2fhow-do-i-prevent-null-fields-in-rows-sql-pivot%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                      Alcedinidae

                      Origin of the phrase “under your belt”?