从SQL Server中挑选出对

时间:2015-03-24 01:17:08

标签: sql-server

我正在从SQL-EX.com

开始练习16
Find the pairs of PC models having identical speeds and RAM.
As a result, each resulting pair is shown only once, i.e. (i, j) but not (j, i).
Result set: model with higher number, model with lower number, speed, and RAM.

我使用了以下查询

SELECT B.code, B.model AS BM, A.code, A.model, A.speed, A.ram 
FROM PC A
JOIN PC B
ON A.speed = B.speed AND A.ram = B.ram
WHERE A.model <> B.model
ORDER BY B.model ASC

enter image description here

如何仅检索BM高于model的对?

2 个答案:

答案 0 :(得分:1)

不使用<>,而是使用<

SELECT
    a.model,
    b.model,
    a.speed,
    a.ram
FROM PC a
INNER JOIN PC b
    ON b.speed = a.speed
    AND b.ram = a.ram
    AND b.model < a.model

答案 1 :(得分:1)

更改此行:

WHERE A.model <> B.model

对此:

WHERE A.model > B.model

您还需要选择正确的列,但正确获取WHERE表达式是困难的部分。