如何汇总按发票分组的成本项目?

时间:2015-05-29 07:46:00

标签: sql sql-server sql-server-2012

下面有两个SQL Server表:

发票

InvoiceId     Amount    [Date]
        1         10    2015-05-28 21:47:50.000 
        2         20    2015-05-28 21:47:50.000
        3         25    2015-05-28 23:25:50.000

InvoiceItem

Id   InvoiceId   Cost
 1           1      8
 2           1      3
 3           1      7
 4           2     15
 5           2     17
 6           3     20
 7           3     22

现在我想JOIN这两个表格ON InvoiceId 并检索以下内容:

    来自发票COUNT [计数] DISTINCT InvoiceId
  1. AS > 来自发票表<{1}} 金额
  2. 金额
  3. SUM 来自 InvoiceItem 表<{1}} 费用
  4. 费用
  5. AS
  6. SUM [日期]
  7. 的一部分

    AS他们HOUR GROUP [日期] 的一部分。

    所需的输出将是:

    BY

    我该怎么做?

2 个答案:

答案 0 :(得分:1)

一种方法是使用派生表:

   SELECT   CAST([Date] AS DATE) AS [Date],
            DATEPART(HOUR,i.[Date]) AS HourOfDay, 
            COUNT(i.InvoiceId) AS NumberOfInvoices,
            SUM(i.Amount) AS Amount,
            SUM(it.Cost) AS Cost
    FROM    invoice i
            INNER JOIN
            (SELECT InvoiceId, SUM(Cost) AS Cost
             FROM invoiceitem
             GROUP BY InvoiceId) it ON i.InvoiceId = it.InvoiceId 
    GROUP BY [Date],DATEPART(HOUR,i.[Date])

或CTE(公用表格表达)

WITH InvoiceCosts (InvoiceId, Cost)
AS
(
    SELECT InvoiceId, SUM(Cost) AS Cost
    FROM invoiceitem
    GROUP BY InvoiceId
)


SELECT  CAST([Date] AS DATE) AS [Date],
        DATEPART(HOUR,i.[Date]) AS HourOfDay, 
        COUNT(i.InvoiceId) AS NumberOfInvoices,
        SUM(i.Amount) AS Amount,
        SUM(ic.Cost) AS Cost
FROM    invoice i
        INNER JOIN
        InvoiceCosts ic ON i.InvoiceId = ic.InvoiceId 
GROUP BY [Date],DATEPART(HOUR,i.[Date])

答案 1 :(得分:0)

         SELECT COUNT (DISTINCT inv.InvoiceId) [Count],
                SUM (Amount) Amount,
                SUM (Cost) Cost,
                datepart(HOUR, inv.[Date]) HourOfDay
           FROM Invoice inv
     INNER JOIN InvoiceItem itm
             ON inv.InvoiceId = itm.InvoiceId
       GROUP BY datepart(HOUR, inv.[Date]);