MySQL - 只计算一个与连接不同的值

时间:2014-11-07 10:05:36

标签: mysql join group-by left-join distinct

我有5张桌子。

auction, seller , auction_person,  person_company, quote

例如,对于一次拍卖(一个卖家),我在auction_person中有4个人(来自同一家公司),但并非所有人都可以报价。

auction_person
---------------
id, auction, seller, person, person_company, can_quote
-----------------------------------------------------
1   | 1      | 1|    1  |   3           |    1
2   | 1      | 1|    2  |   3           |    0
3   | 1      | 1|    3  |   3           |    1
4   | 1      | 1|    4  |   3           |    1

quote表中我有类似的东西

quote
------------
id,auction_person, auction, price,send_back, accepted
------------------------------------------------------
1  | 1            | 1      | 5$   | 1   | 0
1  | 4            | 1      | 2$   | 0   | 0

有人引用,有些不引用,有些引用是send_back但仍未被接受。

我需要

   1. COUNT(quote)  WHERE send_back = 1
   2. COUNT(accepted) WHERE send_back = 1
   3. COUNT(auction) 
WHERE seller = 1

但是,无论每个公司邀请多少联系人,引用send_back,它都应该算作一个。

因此,如果卖方(id = 1)邀请一个公司的4个人(seller_id = 1),例如3个人引用(2个send_back,1个不是send_back),搜索公司的结果应该是这样的

auction   = 1
send_back = 1
accepted  = 0

这可以只在一个查询中完成吗?

1 个答案:

答案 0 :(得分:0)

我不明白,你有什么问题?

您的需求和结果不一样

what criteria of :
auction   = 1  = COUNT(quote)  WHERE send_back = 1
send_back = 1  = COUNT(send_back)  WHERE send_back = 1
accepted  = 0  = COUNT(accepted) WHERE send_back = 1



Select  Sum(Case    When IsNull(send_back, 0) = 1 Then 1 Else 0 End) as auction,
        Sum(Case    When IsNull(send_back, 0) = 1 Then 1 Else 0 End) as send_back,
        Sum(Case    When IsNull(accepted, 0) = 1 Then 1 Else 0 End) as accepted
from #auction_person a
Left Join #quote b
    On b.auction = a.auction
    And b.Auction_Person = a.Person
WHERE seller = 1