Skip to content
Advertisement

One value for a group of columns in sql

I have the columns like this, all columns coming from three different tables.

GROUPID     COMPANYID CUSTID    DEAL
121         A           1       DEAL1
121         A           1       DEAL2
121         A           1       DEAL3
121         B           2       DEAL1
121         B           2       DEAL2
121         B           2       DEAL3

i want the columns like

GROUPID     COMPANYID CUSTID    DEAL
121         A           1       DEAL1
                                DEAL2
                                DEAL3
            B           2       DEAL1
                                DEAL2
                                DEAL3

Can you help me with this?

Thanks

Advertisement

Answer

i am just enhancing Tim answer by adding lag() window function

WITH yourTable AS (
    SELECT 121 AS GROUPID, 'A' AS COMPANYID, 1 AS CUSTID, 'DEAL1' AS DEAL FROM dual UNION ALL
    SELECT 121, 'A', 1, 'DEAL2' FROM dual UNION ALL
    SELECT 121, 'A', 1, 'DEAL3' FROM dual UNION ALL
    SELECT 121, 'B', 2, 'DEAL1' FROM dual UNION ALL
    SELECT 121, 'B', 2, 'DEAL2' FROM dual UNION ALL
    SELECT 121, 'B', 2, 'DEAL3' FROM dual UNION ALL
    SELECT 123, 'c', 2, 'DEAL1' FROM dual UNION ALL
    SELECT 123, 'c', 2, 'DEAL2' FROM dual
),
cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY GROUPID, COMPANYID, CUSTID ORDER BY DEAL) rn
    FROM yourTable t
)
,cte1 as(
SELECT
    GROUPID,
    CASE WHEN rn = 1 THEN COMPANYID END AS COMPANYID,
    CASE WHEN rn = 1 THEN CUSTID END AS CUSTID,
    DEAL
FROM cte t
ORDER BY
    GROUPID,
    t.COMPANYID,
    CUSTID,
    DEAL) select case when lag(GROUPID)over(order by GROUPID)=GROUPID
    then null else GROUPID end Gid,COMPANYID,CUSTID,DEAL from cte1

DEMO

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement