如何根据主列返回唯一组合的列表和计数?

问题描述 投票:0回答:1

我有下面的表结构,想要返回基于产品的唯一关系组合的计数。人际关系有 14 个独特的价值

客户ID 关系 产品ID
123 小学 abc
456 中学 abc
789 其他 abc
987 小学 xyz

我想要实现的最终输出是这样的

关系类型 关系计数 产品数量
小学、中学、其他 1 1
小学 1 1
sql amazon-redshift
1个回答
0
投票
SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;

WITH RelationshipCounts AS (
    SELECT 
        product_id,
        STUFF((
            SELECT DISTINCT ', ' + relationship
            FROM Relationships AS inner_table
            WHERE inner_table.product_id = outer_table.product_id
            FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS relationship_type,
        COUNT(DISTINCT relationship) AS relationship_count
    FROM Relationships AS outer_table
    GROUP BY product_id
),
FinalOutput AS (
    SELECT 
        relationship_type,
        SUM(relationship_count) AS relationship_count,
        COUNT(DISTINCT product_id) AS product_count
    FROM RelationshipCounts
    GROUP BY relationship_type
)

SELECT 
    relationship_type, 
    relationship_count, 
    product_count
FROM FinalOutput
ORDER BY relationship_type;

© www.soinside.com 2019 - 2024. All rights reserved.