Domanda

I have a query that I need to denormalize in an interesting way.

Here is the source:

SELECT
  BILL_Invoice.Invoice_Number as AccountNumber,
  replace(convert(varchar(10), dbo.BILL_Invoice.Invoice_Date,101) ,'/','') as AdmitDate,
  BILL_InvoiceCPT.InvoiceCPT_Code AS CPTCode,
  InvoiceCPT_FeeAmount as ItemCharge
FROM
  dbo.BILL_InvoiceCPT 
  LEFT JOIN dbo.BILL_Invoice
  ON dbo.BILL_InvoiceCPT.Invoice_ID = dbo.BILL_Invoice.Invoice_ID

The output looks like this:

AccountNumber | AdmitDate  | CPTCode | ItemCharge
38689         | 02192013   | 99213   |     110.00
38689         | 02192013   | 80053   |       0.00
38689         | 02192013   | 86361   |       0.00
38689         | 02192013   | 85025   |       0.00
38689         | 02192013   | 87536   |       0.00
38689         | 02192013   | 93000   |      25.00

What I need is :

AccountNumber | AdmitDate | TotalCharges | CPTCodes                            | ItemCharges
38689         | 02192013  | 135.00       | 99213;80053;86361;85025;87536;93000 | 110.00;0.00;0.00;0.00;0.00;25.00

This is needed for input into a 3rd party software application. I am not sure quite how to denormalize this information correctly. Would a PIVOT function do this?

È stato utile?

Soluzione 2

You need to do aggregation string concatenation. This is a pain in SQL Server. The result looks something like:

with t as (
      SELECT bi.Invoice_Number as AccountNumber, 
             replace(convert(varchar(10), bi.Invoice_Date,101) ,'/','') as AdmitDate,
             InvoiceCPT_FeeAmount as TotalCharges,
             biCPT.InvoiceCPT_Code AS CPTCode, 
             InvoiceCPT_FeeAmount as ItemCharge
      FROM dbo.BILL_InvoiceCPT bicpt LEFT JOIN
           dbo.BILL_Invoice bi
           ON bicpt.Invoice_ID = bi.Invoice_ID
    )
select accountNumber, admitDate,
       STUFF((select ',' + CAST(totalCharges as varchar(255))
              from t
              where t.AccountNumber = t2.AccountNumber
              for xml path ('')
             ), 1, 1, '') as TotalCharges,
       STUFF((select ',' + CAST(itemCharge as varchar(255))
              from t
              where t.AccountNumber = t2.AccountNumber
              for xml path ('')
             ), 1, 1, '') as ItemCharges
from (select distinct accountNumber, admitDate
      from t
     ) t2

Note: I haven't tested this SQL so it might have syntax errors.

Altri suggerimenti

MySQL has a ready function for this called GROUP_CONCAT!

It would look something like this:

SELECT 
 AccountNumber
,AdmitDate
,SUM(TotalCharges)
,GROUP_CONCAT(CPTCode)
,GROUP_CONCAT(ItemCharges)
FROM tbl
WHERE condition
GROUP BY AccountNumber, AdmitDate
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top