SQL Server中具有多个表的多个聚合函数

时间:2011-04-12 14:32:22

标签: sql-server function aggregate

我正在尝试为输入的人获取数据,我想提取数据为No of of Invoices和No for line items for special person。

输出

Entered_by  No of line items
CD               9
CD               136084
deepa             7
deepa             18
dolly             757
dolly             22350
kroshni         666
kroshni         16161
lokesh           4
lokesh           999
MHeera           639
MHeera             20427
nandini            7
nandini            5318

此处行项目中的数据混合了“否订单项数”和“发票数”计数,我希望显示为

Entered_by  No of line items    No of invoices
CD               136084              9
deepa               18                7
dolly               22350               757

请帮助我这个人... ..

这是T-SQL查询

select ENTERED_BY, count(entered_by) 'NO OF LINE ITEMS'
from im_invoice, im_invoice_line_item, im_invoice_inventory 
where invoice_rid = invoice_fk
and invoice_inventory_rid = invoice_inv_fk
and enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by

union 

select entered_by, count(invoice_num) 'NO OF INVOICES' from im_invoice
where enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by

1 个答案:

答案 0 :(得分:1)

正如Joe所说,如果你给我们一个更详细的描述,我们可以给你更好的答案,但在那之前,快速而肮脏的方法来实现这一点如下:

  1. 摆脱联盟
  2. 将2个查询转换为派生表
  3. 从他们中选择加入entered_by。
  4. 例如

    SELECT LineItems.ENTERED_BY, [NO OF LINE ITEMS], [NO OF INVOICES] 
    FROM
    (SELECT ENTERED_BY,COUNT(entered_by) 'NO OF LINE ITEMS' 
    FROM im_invoice, im_invoice_line_item,im_invoice_inventory   
    WHERE invoice_rid = invoice_fk  
    AND invoice_inventory_rid = invoice_inv_fk
    AND enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())
    GROUP BY entered_by) AS LineItems 
    INNER JOIN 
    (SELECT entered_by, count(invoice_num) 'NO OF INVOICES' 
    FROM im_invoice  
    WHERE enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())  
    GROUP BY entered_by ) AS invoices 
    ON invoices.entered_by = LineItems.ENTERED_BY