SQL Server返回多个值在单个查询中使用来自不同表的COUNT

时间:2015-12-10 10:36:00

标签: sql-server-2012

我在SQL Server 2012数据库中有不同的表,具有以下结构:

  • userstbl拥有用户full_name和ID - >这有牙医的信息。

  • bookingtbl有Id,patient_ID(与另一个表相关,有患者的信息文件),booking_date,InvoiceID(与另一张表Invoice相关)。

  • servicetbl:ID,service_id(与另一个具有服务费用的表相关),booking_ID。

  • invoicetbl:ID,TotalCost。

我希望从我的程序中得到的是返回:

user_ID为DrD,Full_name为DrName,预订次数,服务次数,发票总额之和。

基于给定日期。

我试过以下但是smthn仍然缺失:

create Proc SelectDrWork(@date Date)
as
begin
    select 
        userstbl.[user_id],userstbl.full_name,
        count(bookingtbl.bookingID), 
        count(servicetbl.serviceID),
        sum(invoice.Total)
    from 
        userstbl, bookingtbl, Servicetbl, invoice
    where 
        userstbl.IsActivated = 'True' 
        and userstbl.description = 'Dr'
        and bookingtbl.dr_id = [user_id] 
        and cast(bookingtbl.[date] as date) = cast(@date as date)
        and servicetbl.booking_id = book_number 
        and invoice.inv_id = bookingtbl.invoiceID 
    group by 
        [user_id], book_number, diaganosis_serv_id
end

1 个答案:

答案 0 :(得分:0)

我想出了答案。非常简单:

ALTER Proc SelectDrWork(@date Date)
as
begin
select userstbl.[user_id],userstbl.full_name,count(distinct book_number) as BookingCount,count(service_id)as ServiceCount,sum(invoice.Total) as Total
from userstbl, bookingtbl, diaganosistbl, invoice
where userstbl.IsActivated='True' and userstbl.description='Dr'
and bookingtbl.dr_id=[user_id] 
and cast(bookingtbl.[date] as date)= cast(@date as date)
and diaganosistbl.booking_id=book_number 
and invoice.inv_id=bookingtbl.invoiceID 
group by [user_id],full_name
end