如何生成一个列,其中列的大小是sql中另一列的两倍

时间:2014-02-20 02:16:48

标签: sql sqlite

我有一个示例数据库,您可以在此处查看:https://class.stanford.edu/c4x/Engineering/db/asset/socialdata.html

我正在尝试编写一个执行以下操作的sql语句: / 显示与自己年满两岁的人成为朋友的学生列表。不要多次列出任何一对 /

这是我到目前为止的代码:

SELECT distinct 
  A.name, 
  B.name, 
  A.grade, 
  B.grade 
FROM 
  Highschooler A, 
  Highschooler B, 
  Friend F 
WHERE 
  A.ID = F.ID1 AND 
  B.ID = F.ID2 AND 
  B.grade > A.grade 
ORDER BY 
  B.name, 
  B. grade, 
  A.name, 
  A.grade ASC;

这就是我得到的:

Cassandra   Alexis  9   11
Tiffany         Alexis  9   11
Gabriel         Andrew  9   10
Andrew          Austin  10  11
Andrew          Jordan  10  12
Austin          Kyle    11  12
Jessica         Kyle    11  12

看起来它的工作,但最后四个条目只有1岁,而不是2.任何人都可以帮助引导我朝正确的方向或告诉我,如果我已经正确吗?我感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

尝试:

SELECT distinct 
  A.name, 
  B.name, 
  A.grade, 
  B.grade 
FROM 
  Highschooler A, 
  Highschooler B, 
  Friend F 
WHERE 
  A.ID = F.ID1 AND 
  B.ID = F.ID2 AND 
  B.grade - A.grade >= 2
ORDER BY 
  B.name, 
  B. grade, 
  A.name, 
  A.grade ASC;

答案 1 :(得分:0)

尝试以下

SELECT distinct 
  A.name, 
  B.name, 
  A.grade, 
  B.grade 
FROM 
  Highschooler A, 
  Highschooler B, 
  Friend F 
WHERE 
  A.ID = F.ID1 AND 
  B.ID = F.ID2 AND 
  -- check both ways
  (B.grade - A.grade >= 2 OR  A.grade - B.grade >= 2)
ORDER BY 
  B.name, 
  B. grade, 
  A.name, 
  A.grade ASC

答案 2 :(得分:0)

Select hs1.name, hs1.grade, hs2.name, hs2.grade
From highschooler hs1
join likes L on L.id1 = hs1.id
join highschooler hs2 on L.id2 = hs2.id
Where hs1.grade - hs2.grade >= 2