1. 程式人生 > >sql:分組統計時的查詢及效率

sql:分組統計時的查詢及效率

 一張user表 裡面有id、國籍、出生日期等欄位
現在要統計各個國家成年的人有多少、未成年的人有多少
結果如下圖所示 

第一種寫法:

SELECT 
  gjname,
(select count(0) from criminal_base_info where gjname=baseInfo.gjname and TRUNC(months_between(sysdate,csrq)/12,0)>=18) cn,
(select count(0) from criminal_base_info where gjname=baseInfo.gjname and TRUNC(months_between(sysdate,csrq)/12,0)<18) wcn
FROM
  criminal_base_info baseInfo
where 
gjname is not null
GROUP BY gjname

第二種寫法:

SELECT 
  (A1.gjname),wcn,cn
FROM
  (
    SELECT gjname
    FROM
      criminal_base_info baseInfo
where 
gjname is not null
GROUP BY gjname
) a1
LEFT JOIN (
  SELECT COUNT (baseInfo.id) AS wcn,GJNAME
  FROM
    criminal_base_info baseInfo
  WHERE
  TRUNC(months_between(sysdate,csrq)/12,0)<18
  GROUP BY
    gjname
) a2 ON A1.GJNAME = A2.GJNAME
LEFT JOIN (
  SELECT COUNT (baseInfo.id) AS cn,GJNAME
  FROM
    criminal_base_info baseInfo
  WHERE
  TRUNC(months_between(sysdate,csrq)/12,0)>=18
  GROUP BY
    gjname
) a3 ON A1.GJNAME = A3.gjname

對比一下效率 7000+條資料的情況下
第一種:速度為0.08s~0.1s之間
第二種:速度穩定在0.06s