Removing Sub queries to PIVOT table











up vote
0
down vote

favorite












I have a query that uses sub queries, but I would like to make it more efficient and easier to work. I've been looking at PIVOT logic, but can't seem to be able to get it to work. Below is the original sub query logic, can some one help me or point me in the correct direction.



SELECT 
Parent.id
,[sitecode]
,[started]
,[completed]
,cast(( completed - started) as time)
,[profileId]
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE Child.transactionId =Parent.Id AND child.message like '%Initialized%' AND child.message like '%demographic records%' ORDER BY Child.created DESC) AS Dem
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like '%Initialized%' AND child.message like '%clinical records%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS Clincial
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total valid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS ValidPatientTypes
,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total invalid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS NotValidPatientTypes
FROM [Backend].[dbo].[Transaction] AS Parent
where completed > '2018-11-17 00:00:00.00' AND transactionType = 'BulkImport' AND profileId = 122
order by sitecode, completed desc


Any help thanks.
Even if Pivot would not work, can someone point me to a better logic










share|improve this question




























    up vote
    0
    down vote

    favorite












    I have a query that uses sub queries, but I would like to make it more efficient and easier to work. I've been looking at PIVOT logic, but can't seem to be able to get it to work. Below is the original sub query logic, can some one help me or point me in the correct direction.



    SELECT 
    Parent.id
    ,[sitecode]
    ,[started]
    ,[completed]
    ,cast(( completed - started) as time)
    ,[profileId]
    ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE Child.transactionId =Parent.Id AND child.message like '%Initialized%' AND child.message like '%demographic records%' ORDER BY Child.created DESC) AS Dem
    ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like '%Initialized%' AND child.message like '%clinical records%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS Clincial
    ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total valid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS ValidPatientTypes
    ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total invalid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS NotValidPatientTypes
    FROM [Backend].[dbo].[Transaction] AS Parent
    where completed > '2018-11-17 00:00:00.00' AND transactionType = 'BulkImport' AND profileId = 122
    order by sitecode, completed desc


    Any help thanks.
    Even if Pivot would not work, can someone point me to a better logic










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have a query that uses sub queries, but I would like to make it more efficient and easier to work. I've been looking at PIVOT logic, but can't seem to be able to get it to work. Below is the original sub query logic, can some one help me or point me in the correct direction.



      SELECT 
      Parent.id
      ,[sitecode]
      ,[started]
      ,[completed]
      ,cast(( completed - started) as time)
      ,[profileId]
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE Child.transactionId =Parent.Id AND child.message like '%Initialized%' AND child.message like '%demographic records%' ORDER BY Child.created DESC) AS Dem
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like '%Initialized%' AND child.message like '%clinical records%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS Clincial
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total valid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS ValidPatientTypes
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total invalid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS NotValidPatientTypes
      FROM [Backend].[dbo].[Transaction] AS Parent
      where completed > '2018-11-17 00:00:00.00' AND transactionType = 'BulkImport' AND profileId = 122
      order by sitecode, completed desc


      Any help thanks.
      Even if Pivot would not work, can someone point me to a better logic










      share|improve this question















      I have a query that uses sub queries, but I would like to make it more efficient and easier to work. I've been looking at PIVOT logic, but can't seem to be able to get it to work. Below is the original sub query logic, can some one help me or point me in the correct direction.



      SELECT 
      Parent.id
      ,[sitecode]
      ,[started]
      ,[completed]
      ,cast(( completed - started) as time)
      ,[profileId]
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE Child.transactionId =Parent.Id AND child.message like '%Initialized%' AND child.message like '%demographic records%' ORDER BY Child.created DESC) AS Dem
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like '%Initialized%' AND child.message like '%clinical records%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS Clincial
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total valid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS ValidPatientTypes
      ,(SELECT TOP 1 CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000)) FROM [backend].[dbo].[Transaction_StatusMessage] AS Child WHERE child.message like 'Total invalid patient types:%' AND Child.transactionId =Parent.Id ORDER BY Child.created DESC) AS NotValidPatientTypes
      FROM [Backend].[dbo].[Transaction] AS Parent
      where completed > '2018-11-17 00:00:00.00' AND transactionType = 'BulkImport' AND profileId = 122
      order by sitecode, completed desc


      Any help thanks.
      Even if Pivot would not work, can someone point me to a better logic







      sql sql-server select subquery pivot






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 days ago

























      asked 2 days ago









      Chris Cooper

      17212




      17212
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          You can convert those sub-queries to OUTER APPLY



          SELECT 
          Parent.id
          ,[sitecode]
          ,[started]
          ,[completed]
          ,cast(( completed - started) as time)
          ,[profileId]
          ,Child.Dem
          ,Child.Clincial
          ,Child.ValidPatientTypes
          ,Child.NotValidPatientTypes
          FROM [Backend].[dbo].[Transaction] AS Parent
          OUTER APPLY
          (
          SELECT TOP 1
          MAX (CASE WHEN Child.message like '%Initialized%' AND Child.message like '%demographic records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000))
          END) AS Dem,
          MAX (CASE WHEN Child.message like '%Initialized%' AND child.message like '%clinical records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000))
          END) AS Clinical,
          MAX (CASE WHEN Child.message like 'Total valid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000))
          END) AS ValidPatientTypes,
          MAX (CASE WHEN Child.message like 'Total invalid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000))
          END) AS NotValidPatientTypes
          FROM [backend].[dbo].[Transaction_StatusMessage] AS Child
          WHERE Child.transactionId = Parent.Id
          ORDER BY Child.created DESC
          ) Child
          WHERE completed > '2018-11-17 00:00:00.00'
          AND transactionType = 'BulkImport'
          AND profileId = 122
          ORDER BY sitecode, completed desc





          share|improve this answer





















          • Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
            – Chris Cooper
            2 days ago











          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',
          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%2f53410261%2fremoving-sub-queries-to-pivot-table%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          You can convert those sub-queries to OUTER APPLY



          SELECT 
          Parent.id
          ,[sitecode]
          ,[started]
          ,[completed]
          ,cast(( completed - started) as time)
          ,[profileId]
          ,Child.Dem
          ,Child.Clincial
          ,Child.ValidPatientTypes
          ,Child.NotValidPatientTypes
          FROM [Backend].[dbo].[Transaction] AS Parent
          OUTER APPLY
          (
          SELECT TOP 1
          MAX (CASE WHEN Child.message like '%Initialized%' AND Child.message like '%demographic records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000))
          END) AS Dem,
          MAX (CASE WHEN Child.message like '%Initialized%' AND child.message like '%clinical records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000))
          END) AS Clinical,
          MAX (CASE WHEN Child.message like 'Total valid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000))
          END) AS ValidPatientTypes,
          MAX (CASE WHEN Child.message like 'Total invalid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000))
          END) AS NotValidPatientTypes
          FROM [backend].[dbo].[Transaction_StatusMessage] AS Child
          WHERE Child.transactionId = Parent.Id
          ORDER BY Child.created DESC
          ) Child
          WHERE completed > '2018-11-17 00:00:00.00'
          AND transactionType = 'BulkImport'
          AND profileId = 122
          ORDER BY sitecode, completed desc





          share|improve this answer





















          • Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
            – Chris Cooper
            2 days ago















          up vote
          0
          down vote



          accepted










          You can convert those sub-queries to OUTER APPLY



          SELECT 
          Parent.id
          ,[sitecode]
          ,[started]
          ,[completed]
          ,cast(( completed - started) as time)
          ,[profileId]
          ,Child.Dem
          ,Child.Clincial
          ,Child.ValidPatientTypes
          ,Child.NotValidPatientTypes
          FROM [Backend].[dbo].[Transaction] AS Parent
          OUTER APPLY
          (
          SELECT TOP 1
          MAX (CASE WHEN Child.message like '%Initialized%' AND Child.message like '%demographic records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000))
          END) AS Dem,
          MAX (CASE WHEN Child.message like '%Initialized%' AND child.message like '%clinical records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000))
          END) AS Clinical,
          MAX (CASE WHEN Child.message like 'Total valid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000))
          END) AS ValidPatientTypes,
          MAX (CASE WHEN Child.message like 'Total invalid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000))
          END) AS NotValidPatientTypes
          FROM [backend].[dbo].[Transaction_StatusMessage] AS Child
          WHERE Child.transactionId = Parent.Id
          ORDER BY Child.created DESC
          ) Child
          WHERE completed > '2018-11-17 00:00:00.00'
          AND transactionType = 'BulkImport'
          AND profileId = 122
          ORDER BY sitecode, completed desc





          share|improve this answer





















          • Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
            – Chris Cooper
            2 days ago













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          You can convert those sub-queries to OUTER APPLY



          SELECT 
          Parent.id
          ,[sitecode]
          ,[started]
          ,[completed]
          ,cast(( completed - started) as time)
          ,[profileId]
          ,Child.Dem
          ,Child.Clincial
          ,Child.ValidPatientTypes
          ,Child.NotValidPatientTypes
          FROM [Backend].[dbo].[Transaction] AS Parent
          OUTER APPLY
          (
          SELECT TOP 1
          MAX (CASE WHEN Child.message like '%Initialized%' AND Child.message like '%demographic records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000))
          END) AS Dem,
          MAX (CASE WHEN Child.message like '%Initialized%' AND child.message like '%clinical records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000))
          END) AS Clinical,
          MAX (CASE WHEN Child.message like 'Total valid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000))
          END) AS ValidPatientTypes,
          MAX (CASE WHEN Child.message like 'Total invalid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000))
          END) AS NotValidPatientTypes
          FROM [backend].[dbo].[Transaction_StatusMessage] AS Child
          WHERE Child.transactionId = Parent.Id
          ORDER BY Child.created DESC
          ) Child
          WHERE completed > '2018-11-17 00:00:00.00'
          AND transactionType = 'BulkImport'
          AND profileId = 122
          ORDER BY sitecode, completed desc





          share|improve this answer












          You can convert those sub-queries to OUTER APPLY



          SELECT 
          Parent.id
          ,[sitecode]
          ,[started]
          ,[completed]
          ,cast(( completed - started) as time)
          ,[profileId]
          ,Child.Dem
          ,Child.Clincial
          ,Child.ValidPatientTypes
          ,Child.NotValidPatientTypes
          FROM [Backend].[dbo].[Transaction] AS Parent
          OUTER APPLY
          (
          SELECT TOP 1
          MAX (CASE WHEN Child.message like '%Initialized%' AND Child.message like '%demographic records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'demographic records',''))) AS NVarchar(4000))
          END) AS Dem,
          MAX (CASE WHEN Child.message like '%Initialized%' AND child.message like '%clinical records%'
          THEN CAST(RTRIM(LTRIM(REPLACE(REPLACE(CAST(Child.message as NVarchar(4000)) , 'Initialized', ''),'clinical records',''))) AS NVarchar(4000))
          END) AS Clinical,
          MAX (CASE WHEN Child.message like 'Total valid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total valid patient types:',''))) AS NVarchar(4000))
          END) AS ValidPatientTypes,
          MAX (CASE WHEN Child.message like 'Total invalid patient types:%'
          THEN CAST(RTRIM(LTRIM(REPLACE(CAST(Child.message as NVarchar(4000)),'Total invalid patient types:',''))) AS NVarchar(4000))
          END) AS NotValidPatientTypes
          FROM [backend].[dbo].[Transaction_StatusMessage] AS Child
          WHERE Child.transactionId = Parent.Id
          ORDER BY Child.created DESC
          ) Child
          WHERE completed > '2018-11-17 00:00:00.00'
          AND transactionType = 'BulkImport'
          AND profileId = 122
          ORDER BY sitecode, completed desc






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 days ago









          Squirrel

          11.5k22027




          11.5k22027












          • Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
            – Chris Cooper
            2 days ago


















          • Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
            – Chris Cooper
            2 days ago
















          Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
          – Chris Cooper
          2 days ago




          Thanks Squirrel, this help a lot. I was having a problem where a sub query was returning a null and I wanted to remove that row from the main results.. Again thanks
          – Chris Cooper
          2 days ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410261%2fremoving-sub-queries-to-pivot-table%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

          Contact image not getting when fetch all contact list from iPhone by CNContact

          count number of partitions of a set with n elements into k subsets

          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks