具有COUNT和BLOB列的唯一行 - DB2

时间:2012-04-03 16:01:54

标签: sql count db2 blob distinct

我有一个BLOB列,我希望与其他列同时选择,另一个表中的关联行数COUNT。这就是我所拥有的:

SELECT locations.id, locations.name, photo,
    COUNT(items.id) OVER (PARTITION BY locations.id) AS num_items
FROM locations
LEFT OUTER JOIN items ON locations.id = items.location_id
ORDER BY locations.name ASC

photo是BLOB列。此查询获取了我想要的所有数据,但我看到每个location x 行,其中 x 是与item相关联的行数location

所以我得到了:

id          name          photo          num_items
1           location1                    3
1           location1                    3
1           location1                    3
2           location2                    1
3           location3                    2
3           location3                    2
4           location4                    0

我想要的是什么:

id          name          photo          num_items
1           location1                    3
2           location2                    1
3           location3                    2
4           location4                    0

问题是您无法在DISTINCT列上执行GROUP BYMINBLOB

1 个答案:

答案 0 :(得分:1)

我似乎总是在发布后立即找出答案。 :P

SELECT location_data.*, photo
FROM (
    SELECT locations.id, locations.name, COUNT(DISTINCT items.id) AS num_items
    FROM locations
    LEFT OUTER JOIN items ON locations.id = items.location_id
    GROUP BY locations.id, locations.name
) location_data
INNER JOIN (
    SELECT locations.id, photo
    FROM locations
) photo_data ON location_data.id = photo_data.id
ORDER BY name ASC