计数返回0()

时间:2012-02-21 08:41:35

标签: mysql

我见过类似的问题,但很多都是不同的情况,我不能让它像我想要的那样工作,所以我来这里寻求帮助。

用户有一些他们在一定时期内居住过的城市。

如何计算0到他们属于但在BETWEEN个日期之外的所有其他城市?

SELECT cityname, COUNT( cityname ) AS city_count

FROM cities

LEFT OUTER JOIN people ON cities.id = people.cityid

WHERE firstname =  'John' AND lastname =  'Doe'

AND RESIDENCY_DATE

BETWEEN  '1996-08-01'

AND  '1997-05-31'

GROUP BY cityname

查询输出:

    city | city_count
  ___________________

  cali          1
  seattle       2

预期产出:

    city | city_count
  ___________________

  cali          1
  seattle       2
  washington    0
  new york      0

等等。

我希望它可以计算日期之间的任何数字,但会将0返回到他们所居住的所有其他城市。

people.cityid列中的所有行)

2 个答案:

答案 0 :(得分:1)

以下内容应该有效。还冒昧地清理了BETWEEN逻辑,以确保它符合1997-05-31的标准。

这将选择所有城市,然后计算符合标准的人

SELECT 
    cities.cityname, 
    COALESCE(COUNT( inTimePeriod.id ),0) AS city_count

FROM cities

// Find all cities the user has lived in

INNER JOIN people AS hasLivedIn
    ON hasLivedIn.cityid = cities.id
    AND people.firstname =  'John'
    AND people.lastname =  'Doe'

// Now rejoin the ones that they've lived in in the specified time

LEFT JOIN people AS inTimePeriod
    ON inTimePeriod.cityid = hasLivedIn.cityid
    AND inTimePeriod.RESIDENCY_DATE BETWEEN DATE('1996-08-01') AND DATE('1997-05-31')

GROUP BY cities.cityname

答案 1 :(得分:0)

如果没有匹配的行,请使用COUNT(DISTINCT)返回0。

尝试以下:

  SELECT cityname, COUNT( distinct cityname ) AS city_count
  FROM cities
  LEFT OUTER JOIN people ON cities.id = people.cityid
  WHERE firstname =  'John' AND lastname =  'Doe'
  AND RESIDENCY_DATE
  BETWEEN  '1996-08-01'
  AND  '1997-05-31'
  GROUP BY cityname