   05:56

# Exercise #16

Find the pairs of PC models having similar 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 high number, model with low number, speed, and RAM.

Here is the frequently proposed solution:

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

I really don't know, what was the cause to decide outputting only models with maximum and minimum numbers for each coinciding pair of values {speed, ram}. It is possible that the result of inaccurate query on available database is misleading.

In this task, it is needed to order all the models, but not only maximum and minimum of these. Extremal characteristics are mentioned for uniqueness, i.e. to get the pairs of models once , for example:

1122 1121
but not

1121 1122

So, if three models 1122, 1121, and 1135 have alike features, the result will be as follows:

1135 1122
1135 1121
1122 1121

Below is presented almost correct solution, though also the too bulky.

Solution 1.12.2  Console
`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 in subrequest S unique pairs of characteristics (speed, memory) are selected, which coincide for two computers (SUM (speed)/speed = 2) - the sum of identical values divided by this value gives us quantity of the PCs. Though with the same success it was possible to write the following HAVING clause:

`HAVING COUNT(*) = 2`

The subquery joined with the table PC on this characteristics pair twice. In so doing, the second join is only carried out to order the models (L.model <P.model).

The mistake of the given decision consists that the number of the personal computers with identical characteristics may be more than two. In this situation any of such models will not get in result set of the presented solution.

In spite of the fact that the solution is easy to correct, better to rewrite it in not a such superfluous form.

There is one more mistake which is often made in this exercise. It is due to the fact that the PC table may include some computers with same model value. Therefore it is necessary to exclude possible duplicates of required pairs.

T&S

To solve the problem on SQL-EX.RU

Tags
The book was updated
month ago