拥有2种或更多官方语言且非正式语言数量增加2倍的国家/地区列表

时间:2018-06-10 09:38:55

标签: mysql sql database

我有下一个模型的任务:

DB model

下一步任务:输出具有两种或更多官方语言的国家列表,其中非官方语言的数量至少是官方语言的两倍。

任务似乎很简单,但我有错误。 我接下来试过了:

(define (both-same-sign a b)
  (if (and (> a 0) (> b 0)) #t
  (if (and (< a 0) (< b 0)) #t
  #f)))

(define (make-positive n)
  (if (< n 0) (- n)
  n))

(define (multiply x y)
  (define a (make-positive x))
  (define b (make-positive y))
  (define (multiplier a b)
    (if (or (= a 0) (= b 0)) 0
    (+ a (multiplier a (- b 1)))))
  (define result (multiplier a b))
  (if (both-same-sign x y) result
   (- result)))

但我只有一次退货。

列出所有拥有2种以上官方语言的国家/地区:

SELECT name, countrylanguage.*
FROM country, countrylanguage
WHERE countrycode = code AND isofficial LIKE "t"
GROUP BY isofficial 
HAVING COUNT(*) => 2;

但我应该如何只选择两倍于非官方语言的国家呢?

2 个答案:

答案 0 :(得分:0)

内部查询似乎是最简单的方法。从至少包含两种官方语言的国家/地区列表开始:

select countrycode, count(1)
from countrylangauge
where isofficial
group by countrycode
having count(1) >= 2

加入类似的查询可以获得非正式的语言计数

select official.countrycode, 
       official.number 'Official Langs',
       unofficual.number 'Unofficual Langs'
from (select countrycode, count(1) as number
      from countrylangauge
      where isofficial
      group by countrycode
      having count(1) >= 2
     ) offical
   inner join (select countrycode, count(1) as number
      from countrylangauge
      where not isofficial
      group by countrycode
      -- Since min count of offical is 2, and need double unoffical
      -- then need at lease 4 here
      having count(1) >= 4
     ) unoffical
     on unofficual.countrycode = offical.countrycode
          and unofficual.number >= 2*officual.countrycode

欢迎加入country以获取有关该委员会的更多详情。

答案 1 :(得分:0)

也许是这样的?

select * from (
  SELECT
    countrycode, 
    sum(case when isofficial = 1 then 1 else 0 end) as officials,
    sum(case when isofficial = 0 then 1 else 0 end) as nonofficials
  FROM countrylanguage
  GROUP BY countrycode 
) X
where officials >= 2 and nonofficials > officials * 2