02:50

# Exercise #16

Get pairs of PC models with identical speeds and the same RAM capacity. Each resulting pair should be displayed only once, i.e. (i, j) but not (j, i).Result set: model with the bigger number, model with the smaller number, speed, and RAM.

Here is a solution that occurs quite often:

Solution 1.12.1

Console
Execute
`SELECT MAX(model) AS 'model', MIN(model) AS 'model', speed, ramFROM PCGROUP BY speed, ramHAVING MAX(model) > MIN(model);`

I really have no idea why some users output just the maximum and minimum model for each matching pair of speed and ram values. Maybe the correct result returned by such a query for the main database is misleading.

In this task, all models have to be ordered, not just the maximum and the minimum one. Extreme values are mentioned just for the sake of unambiguity, to make it clear a pair of models has to be displayed once, e. g.

1122 1121
but not

1121 1122

Say, if three models 1122, 1121, and 1135 have identical characteristics, the result should look as follows:

1135 1122
1135 1121
1122 1121

The solution presented below is almost correct, albeit somewhat cumbersome.

Solution 1.12.2

Console
Execute
`SELECT P.model, L.model, P.speed, P.ramFROM PC P JOIN      (SELECT speed, ram      FROM PC      GROUP BY speed, ram      HAVING SUM(speed)/speed = 2 AND              SUM(ram)/ram = 2       ) S ON P.speed = S.speed AND              P.ram = S.ram JOIN       PC L ON L.speed = S.speed AND               L.ram = S.ram AND               L.model < P.model;`

Here, the subquery S gets the unique pairs of characteristics (speed, memory) coinciding for two computers (SUM (speed)/speed = 2) - the sum of identical values divided by this value yields the number of PCs. However, one could just as well use the following HAVING clause in this case:

`HAVING COUNT(*) = 2`

The subquery is joined to the PC table PC using this pair of characteristics twice. Thereby, the second join is performed just to order the models (L.model <P.model).

The mistake of this solution is, there may be more than two PCs with identical characteristics. In this case, the query under consideration won’t output any of such models.

In spite of the fact this solution can be corrected easily, it’s preferable to rewrite it in a less redundant form.

One more mistake typical for this exercise is caused by the possible presence of identical computer models in the PC table. Thus, when displaying pairs of PCs you need to remove duplicates.

T&S