按计数选择总和分组记录

时间:2014-03-19 17:44:29

标签: sql oledb

我有一张excel表,其中包含订单发票 每张发票都有以下数据

ID = a unique id for each ID

CUSTOMER = The name of the ID

AMT = The total value of the invoices

DATE = The date of the purchase

以下数据

CID     CUSTOMER    AMT     DATE
1       James           100     1/1/2012
2       Mark            110     1/1/2012
3       John            110     2/1/2012
1       James           200     2/1/2012
3       John            140     2/1/2012
2       Mark            120     3/1/2012

我需要从excel表中选择记录,以便我有这个输出

CID     Customer    INVCOUNT    TotalValue
1       James       2       300     
1       John        2       250     
1       Mark        2       230 

这是我试过的SQL

Select
  i.[CID],
  i.[CUSTOMER],
  Count(i.[CID]) as INVCOUNT,
  sum(i.AMT) as TotalValue
From
  [Invoices] i
Where
  i.[DATE] >= #2/1/2012# And
  i.[DATE] <= #3/1/2012#
Group By
  i.[CID], i.[CUSTOMER]
Having
  Count(i.[CID]) > 1

这是一个excel查询,而不是mysql。我之前使用的标签是错误的。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

获取您指定的输出:

Select
  1 as CID,
  i.[CUSTOMER],
  Count(i.[CID]) as INVCOUNT,
  sum(i.AMT) as TotalValue
From
  [Invoices] i
Where
  i.[DATE] >= #1/1/2012# And
  i.[DATE] <= #3/1/2012#
Group By
  i.[CID], i.[CUSTOMER]
Having
  Count(i.[CID]) > 1

要获得输出,我认为你真的想要:

Select
  i.[CID],
  i.[CUSTOMER],
  Count(i.[CID]) as INVCOUNT,
  sum(i.AMT) as TotalValue
From
  [Invoices] i
Where
  i.[DATE] >= #1/1/2012# And
  i.[DATE] <= #3/1/2012#
Group By
  i.[CID], i.[CUSTOMER]
Having
  Count(i.[CID]) > 1

这应该生成

CID     Customer    INVCOUNT    TotalValue
1       James       2       300     
2       John        2       250     
3       Mark        2       230