Никакие дубликаты в SQL-запросе

Исследования в математике и физике. Существует, вероятно, две альтернативы: C и C++, но такие функции последнего, поскольку инкапсуляция и наследование не очень полезны там. Можно было предпочесть использовать C++ "в качестве лучшего C" или просто оставаться с C.

5
задан Tom H 8 July 2010 в 20:25
поделиться

4 ответа

GROUP BY tblcaritem.caritemid

11
ответ дан 18 December 2019 в 11:58
поделиться

The problem here is just as you describe: you're checking for the uniqueness of the whole row, your dataset ends up looking like this:

CarItemId    CarId
---------    -----
1            1
1            2
1            3
2            1
2            2
3            3

You want unique CarItemIds with no duplicates, meaning that you also want unique CarIds ---- alright, you have 3 CarIds, which one should SQL Server pick?

You don't have much choice here except to aggregate those extra CarIds away:

SELECT tblcaritem.caritemid, max(tblcar.icarid)
FROM tblcaritem
INNER JOIN tblprivatecar ON tblcaritem.partid = tblprivatecar.partid
INNER JOIN tblcar ON tblcaritem.carid = tblcar.carid
WHERE tblcaritem.userid=72
GROUP BY tblcaritem.caritemid
4
ответ дан 18 December 2019 в 11:58
поделиться

You could do an aggregate function on the other row... something like max or min

SELECT tblcaritem.caritemid, max(tblcar.icarid) 
FROM tblcaritem 
INNER JOIN tblprivatecar ON tblcaritem.partid = tblprivatecar.partid 
INNER JOIN tblcar ON tblcaritem.carid = tblcar.carid 
WHERE tblcaritem.userid=72
group by tblcaritem.caritemid;
0
ответ дан 18 December 2019 в 11:58
поделиться

If you put 2 fields in a SELECT DISTINCT query, it will return rows where the combination of the 2 fields is unique, not just where each field is unique.

You are going to have to run 2 separate queries if you want only unique results for each column.

0
ответ дан 18 December 2019 в 11:58
поделиться
Другие вопросы по тегам:

Похожие вопросы: