计算SQL查询中多个不同行的值

时间:2015-12-05 02:23:02

标签: sql sql-server count

我对SQL很新,所以请原谅我缺乏知识。我也是这样做的,所以请不要只给我答案,我想学习。

我有3张表,其中包括Contracts,PaymentTypes,InsuranceCompanies。我正在尝试加入他们,然后显示保险公司推出的付款方式为保险的合同数量。我已经这样做了,但不计算每家保险公司的合同金额。而是计算使用保险的保险公司的数量,并将其纳入每个保险公司的数量。以下是我对SQL Query的看法:

Select Distinct InsuranceCompanies.InsuranceCompany, Count (Contracts.InsuranceID)  as 'Number of contracts'
from  Contracts, PaymentTypes, InsuranceCompanies 
where (Contracts.PaymentTypeID = 3) AND (PaymentTypes.PaymentTypeID = 3) AND (Contracts.PaymentTypeID = PaymentTypes.PaymentTypeID) 
Group by InsuranceCompanies.InsuranceCompany

以下是它的输出:

All Insurance       273
Best Insurance      273
Friendly Insurance  273
Insurance One       273
Safety Insurance    273

所以我的问题是如何计算个别保险公司然后相应地显示它?

我把答案给了我,应用了所有需要的变量,它的功能完美!这是最终的工作查询:

Select i.InsuranceCompany, Count(c.InsuranceID) as 'Number of contracts'
from  Contracts c
join paymenttypes p on p.PaymentTypeID = c.PaymentTypeID
join insurancecompanies i on i.InsuranceID = c.InsuranceID
where c.PaymentTypeID = 3 AND p.PaymentTypeID = 3
Group by i.InsuranceCompany

1 个答案:

答案 0 :(得分:1)

你的查询看起来应该是这样的,但由于我遗漏了你的结构部分,我无法填写on之后的部分

Select i.InsuranceCompany, Count(c.InsuranceID) as 'Number of contracts'
from  Contracts c
join paymenttypes p on p.PaymentTypeID = c.PaymentTypeID
join insurancecompanies i on i.InsuranceID = c.InsuranceID
where c.PaymentTypeID = 3 AND p.PaymentTypeID = 3
Group by i.InsuranceCompany

关于表连接的read