2计数在相同的查询但不同的条件

时间:2012-10-14 13:07:28

标签: mysql count aggregate-functions aggregate

这一直困扰着我:

我想在1张桌子里做2个计数。第一个计算总共有多少个商店,第二个应该计算价格低于tsuppliers的商店总数.lowestprice

所以基本上我想把第二个查询合并到第一个:

SELECT tshops.shopID, tshops.OfficialName, tsuppliershopinfo.ContactName,   tsuppliershopinfo.ContactMail, Count(distinct tresults.pID) AS AantalVanpID
FROM (tsupplierproducts 
    INNER JOIN tresults ON tsupplierproducts.pID = tresults.pID)     
    INNER JOIN (tsuppliershopinfo INNER JOIN tshops ON tsuppliershopinfo.shopID = tshops.shopID) ON tresults.shopID = tsuppliershopinfo.shopID
WHERE (((tsupplierproducts.supplierID)=2)) AND tresults.starttime BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND DATE_ADD(CURDATE(),INTERVAL 1 DAY)
GROUP BY tshops.shopID, tshops.OfficialName, tsuppliershopinfo.ContactName, tsuppliershopinfo.ContactMail;

第二个(注意where子句中只有一个额外条件):

SELECT tresults.shopID, Count(distinct tresults.pID) AS AantalVanpID
FROM tsupplierproducts INNER JOIN tresults ON tsupplierproducts.pID = tresults.pID
WHERE (((tsupplierproducts.supplierID)=2) AND ((tresults.Price)<tsupplierproducts.LowestPrice)) AND tresults.starttime BETWEEN DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND DATE_ADD(CURDATE(),INTERVAL 1 DAY)
GROUP BY tresults.shopID;

如何将第二个查询合并到第一个查询中?

谢谢!

1 个答案:

答案 0 :(得分:1)

SELECT 
    tshops.shopID, 
    tshops.OfficialName, 
    tsuppliershopinfo.ContactName,   
    tsuppliershopinfo.ContactMail, 
    Count(distinct tresults.pID) AS AantalVanpID,
    Count(distinct 
        case when tresults.Price < tsupplierproducts.LowestPrice then tresult.pID end
        ) as AantalVanpID_2
FROM
    tsupplierproducts 
    INNER JOIN tresults ON tsupplierproducts.pID = tresults.pID   
    INNER JOIN tsuppliershopinfo ON tresults.shopID = tsuppliershopinfo.shopID
    INNER JOIN tshops ON tsuppliershopinfo.shopID = tshops.shopID
WHERE 
    tsupplierproducts.supplierID = 2
    AND 
    tresults.starttime BETWEEN 
        DATE_SUB(CURDATE(), INTERVAL 14 DAY) AND DATE_ADD(CURDATE(),INTERVAL 1 DAY)
GROUP BY 
    tshops.shopID, 
    tshops.OfficialName, 
    tsuppliershopinfo.ContactName, 
    tsuppliershopinfo.ContactMail