SQL连接条件

时间:2011-06-24 19:06:15

标签: sql count group-by inner-join

三张桌子

cats
=============
id
cat_herder_id
size
color
birthday

collars
=============
id
cat_id
diameter
color
material

cat_herders
=============
id
name
age
height

我想为每只超过一米高的猫牧民争取一排,计算出2月份出生的猫的数量,这些猫是橙色的,黑色项圈属于那个牧民,还有所有猫的数量那些属于每个牧民的蓝色衣领是橙色的,我将如何进行那种查询。

我认为我不能简单地在where语句中指定,因为我的计数似乎已关闭,我正在按cat_herders.id进行分组

编辑:到目前为止,我所拥有的消毒程度较低,抽象程度较低:

SELECT company.tblusers.first_name, company.tblusers.last_name, company.tblusers.userid, SUM(db.tasks.estimated_nonrecurring+db.tasks.estimated_recurring), COUNT(sugarcrm2.ncr_ncr.id),  
SUM(db.batch_log.time_elapsed) FROM company.tblusers 
INNER JOIN db.batch_log ON company.tblusers.userid = db.batch_log.userid 
INNER JOIN db.tasks ON db.batch_log.batch_id = db.tasks.batch_id
INNER JOIN sugarcrm2.ncr_ncr ON company.tblusers.first_name + " " + company.tblusers.first_name = sugarcrm2.ncr_ncr.employee
WHERE  departmentid = 8 AND DATE(db.batch_log.start_time) =  DATE(NOW()) GROUP BY userid

1 个答案:

答案 0 :(得分:5)

注意:根据您的RDBMS和cats.birthday列的数据类型,您可能需要调整此查询以提取出生月份,但这可以为您提供一般的想法。

SELECT ch.name,
       SUM(CASE WHEN c.color = 'orange' AND cl.color = 'black' AND c.birthday = 'February' THEN 1 ELSE 0 END) AS OrangeCatsBlackCollarsFeb,
       SUM(CASE WHEN c.color = 'orange' AND cl.color = 'blue' THEN 1 ELSE 0 END) AS OrangeCatsBlueCollars 
    FROM cat_herders ch
        LEFT JOIN cats c
            INNER JOIN collars cl
                ON c.id = cl.cat_id
            ON ch.id = c.cat_herder_id
    WHERE ch.height > 1 /* in meters */
    GROUP BY ch.name