计算具有相同关系的行

时间:2015-09-08 04:26:11

标签: sql sql-server

我有三张桌子。调色板,颜色和关系表palette_color。就像这个样本:

http://sqlfiddle.com/#!6/fe832/2

我想计算关系表中具有相同颜色的调色板。正如您在示例中看到的那样,我已经在做了。但我相信我的方法效率不高。运行需要将近2秒钟。

我正在使用SQL Server。

这是我计算行数的地方:

(
SELECT count(DISTINCT palette_id) as total FROM palette_color COLOR
    WHERE NOT EXISTS
        (( (SELECT color_id FROM palette_color WHERE palette_id = PALETTE.id) EXCEPT (SELECT color_id FROM palette_color WHERE palette_id = COLOR.palette_id) )
        UNION ALL
        ( (SELECT color_id FROM palette_color WHERE palette_id = COLOR.palette_id) EXCEPT (SELECT color_id FROM palette_color WHERE palette_id = PALETTE.id) ))
 ) as total

在where子句中,我确保只有第一个调色板出现在结果

WHERE  id =
(
    SELECT MIN(palette_id) FROM palette_color COLOR
        WHERE NOT EXISTS
            (( (SELECT color_id FROM palette_color WHERE palette_id = PALETTE.id) EXCEPT (SELECT color_id FROM palette_color WHERE palette_id = COLOR.palette_id) )
            UNION ALL
            ( (SELECT color_id FROM palette_color WHERE palette_id = COLOR.palette_id) EXCEPT (SELECT color_id FROM palette_color WHERE palette_id = PALETTE.id) ))
)

2 个答案:

答案 0 :(得分:4)

在这里,我使用color_id

创建palete_id中所有FOR XML PATH的字符串列表

然后分组并计算每组颜色。

SQL FIDDLE DEMO(12ms)

with cList as (
    SELECT  p.id palette_id, 
            STUFF(( SELECT ',' + CAST(pc.color_id as varchar(10) )
                    FROM palette_color pc
                    WHERE pc.palette_id = p.id
                    ORDER BY pc.color_id
                  FOR
                    XML PATH('')
                  ), 1, 1, '') AS ColorList
    FROM palette p
)
select min(palette_id) palette_id, ColorList, count(*) Total
from cList
group by ColorList

答案 1 :(得分:2)

您可以使用FOR XML PATH执行此操作:

查询1

SELECT MIN(palette_id), count(*), colors
FROM (
SELECT id as palette_id,
colors = STUFF((
          SELECT ',' + convert(nvarchar(20), pc.color_id)
          FROM palette_color pc
          WHERE pc.palette_id = palette.id
          ORDER BY pc.color_id
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM palette) a
GROUP BY colors

<强> Results

|    |    |    colors |
|----|----|-----------|
|  1 | 15 |       1,2 |
|  6 | 60 |     1,2,3 |
| 26 |  6 |   1,2,3,4 |
| 46 | 42 | 1,2,3,4,5 |
| 28 | 18 |     1,3,4 |
| 34 | 36 |   1,3,4,5 |

作为奖励,此解决方案为您提供调色板中使用的实际颜色