4

我有一个查询需要以一种有趣的方式进行非规范化。

这是来源:

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

输出如下所示:

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

我需要的是:

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

这是输入第 3 方软件应用程序所必需的。我不太确定如何正确地非规范化这些信息。PIVOT 函数会这样做吗?

4

2 回答 2

5

MySQL为此提供了一个名为GROUP_CONCAT的现成函数!

它看起来像这样:

SELECT 
 AccountNumber
,AdmitDate
,SUM(TotalCharges)
,GROUP_CONCAT(CPTCode)
,GROUP_CONCAT(ItemCharges)
FROM tbl
WHERE condition
GROUP BY AccountNumber, AdmitDate
于 2013-02-20T16:42:43.640 回答
2

您需要进行聚合字符串连接。这是 SQL Server 中的一个痛点。结果看起来像:

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

注意:我没有测试过这个 SQL,所以它可能有语法错误。

于 2013-02-20T16:30:03.743 回答