需要列出最受欢迎的汽车

时间:2014-11-13 14:50:10

标签: sql oracle

这是我到目前为止所拥有的

SELECT person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL
FROM person,
  client,
  policy,
  INSURED_ITEM,
  INSURED_BY
WHERE person.PID    = client.PID
AND client.CID      = insured_by.cid
AND INSURED_BY.PNO  = policy.PNO
AND insured_item.id = policy.id
AND person.SUBURB   = 'Randwick'
ORDER BY COUNT(*) DESC ;
我试图做的是列出兰德威克最受欢迎的汽车。

这是纠正了吗?

2 个答案:

答案 0 :(得分:1)

您需要使用group by才能使用聚合计数(*)

SELECT person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL,
  COUNT(*) AS PopularityIndex
FROM person
  JOIN client ON person.PID    = client.PID
  JOIN INSURED_BY ON client.CID      = insured_by.cid
  JOIN policy ON INSURED_BY.PNO  = policy.PNO
  JOIN INSURED_ITEM ON insured_item.id = policy.id
WHERE person.SUBURB   = 'Randwick'
GROUP BY person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL
ORDER BY PopularityIndex DESC ;

根据您的评论,要返回Oracle中的前三名,您可以将其添加到select语句

SELECT *
FROM ( SELECT person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL,
  COUNT(*) AS PopularityIndex
FROM person
  JOIN client ON person.PID    = client.PID
  JOIN INSURED_BY ON client.CID      = insured_by.cid
  JOIN policy ON INSURED_BY.PNO  = policy.PNO
  JOIN INSURED_ITEM ON insured_item.id = policy.id
WHERE person.SUBURB   = 'Randwick'
GROUP BY person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL
ORDER BY PopularityIndex DESC )
WHERE ROWNUM >= 3;

您还可以添加一个having子句,允许您在PopularityIndex上设置阈值

SELECT person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL,
  COUNT(*) AS PopularityIndex
FROM person
  JOIN client ON person.PID    = client.PID
  JOIN INSURED_BY ON client.CID      = insured_by.cid
  JOIN policy ON INSURED_BY.PNO  = policy.PNO
  JOIN INSURED_ITEM ON insured_item.id = policy.id
WHERE person.SUBURB   = 'Randwick'
GROUP BY person.PID,
  person.FIRSTNAME,
  person.SUBURB,
  INSURED_ITEM.MODEL
HAVING COUNT(*) > 3
ORDER BY PopularityIndex DESC ;

答案 1 :(得分:0)

你给我的帮助但是我改变它以适应,

SELECT 
INSURED_ITEM.MODEL,
COUNT(*) as POPULAR
FROM person
JOIN client ON person.PID    = client.PID
JOIN INSURED_BY ON client.CID      = insured_by.cid
JOIN policy ON INSURED_BY.PNO  = policy.PNO
JOIN INSURED_ITEM ON insured_item.id = policy.id
WHERE person.SUBURB   = 'Randwick'
GROUP BY 
INSURED_ITEM.MODEL
having count(*) > = 2
order by count(*) desc;