查询与count子查询,内部联接和组

时间:2011-05-02 17:27:54

标签: sql postgresql group-by subquery

我绝对是SQL的菜鸟,我一直忙着在Postgresql中用以下表结构编写一个复杂的查询:

CREATE TABLE reports
(
  reportid character varying(20) NOT NULL,
  userid integer NOT NULL,
  reporttype character varying(40) NOT NULL,  
)

CREATE TABLE users
(
  userid serial NOT NULL,
  username character varying(20) NOT NULL,
)

查询的目的是获取每个用户的报告类型数量并将其显示在一列中。有三种不同类型的报告。

使用group-by的简单查询将解决问题,但会将其显示在不同的行中:

select count(*) as Amount,
       u.username,
       r.reporttype 
from reports r,
     users u 
where r.userid=u.userid 
group by u.username,r.reporttype 
order by u.username

3 个答案:

答案 0 :(得分:15)

SELECT
  username,
  (
  SELECT 
    COUNT(*)
  FROM reports 
  WHERE users.userid = reports.userid && reports.reporttype = 'Type1'
  ) As Type1,
  (
  SELECT 
    COUNT(*)
  FROM reports 
  WHERE users.userid = reports.userid && reports.reporttype = 'Type2'
  ) As Type2,
  (
  SELECT 
    COUNT(*)
  FROM reports 
  WHERE users.userid = reports.userid && reports.reporttype = 'Type3'
  ) As Type3
FROM
  users
WHERE 
  EXISTS(
    SELECT 
      NULL
    FROM 
      reports
    WHERE 
       users.userid = reports.userid
  )

答案 1 :(得分:6)

SELECT
  u.username,
  COUNT(CASE r.reporttype WHEN 1 THEN 1 END) AS type1Qty,
  COUNT(CASE r.reporttype WHEN 2 THEN 1 END) AS type2Qty,
  COUNT(CASE r.reporttype WHEN 3 THEN 1 END) AS type3Qty
FROM reports r
  INNER JOIN users u ON r.userid = u.userid 
GROUP BY u.username

如果服务器的SQL方言要求CASE表达式中存在ELSE分支,请在每ELSE NULL之前添加END

答案 2 :(得分:0)

如果您正在寻找“每个用户的报告类型数量”,您将期望看到针对每个用户的数字,1,2或3(假设有三种不同类型的报告)。您不会期望reporttype(它只会被计算不显示),因此您不需要在查询的SELECT或GROUP BY部分中使用reporttype。

而是使用COUNT(DISTINCT r.reporttype)来计算每个用户使用的不同报告类型的数量。

SELECT
 COUNT(DISTINCT r.reporttype) as Amount
,u.username
FROM users u 
INNER JOIN reports r
ON r.userid=u.userid 
GROUP BY
 u.username
ORDER BY u.username