Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL to combine data for single row per object
    primarykey
    data
    text
    <p>I know this must be a common problem, but I'm not sure where to go. This occurs a few times inside a big nasty query, so here is the problem simplified. I just want one row per object, but the null on ColorOther gives me two rows. </p> <p>I can think of a few things to try wrapping a query around this, but there must be something simpler... I'm off to read up on pivots.</p> <p>Table structure</p> <pre><code>CREATE TABLE [dbo].[Colors]( [ColorId] [int] IDENTITY(1,1) NOT NULL, [ColoredObjectId] [int] NOT NULL, [ColorCode] [int] NOT NULL, [ColorOther] [nvarchar](50) NULL, CONSTRAINT [PK_Colors] PRIMARY KEY CLUSTERED ([ColorId] ASC) </code></pre> <p>Source data</p> <pre><code>ColorId ColoredObjectId ColorCode ColorOther ----------- --------------- ----------- ---------- 1 1 1 NULL 2 1 2 NULL 3 1 4 purple 4 2 2 NULL 5 2 3 NULL 6 2 4 orange 7 3 1 NULL 8 3 3 NULL 9 3 4 green </code></pre> <p>Query</p> <pre><code>SELECT ColoredObjectId , ColorOther , MAX(CASE WHEN ColorCode = 1 THEN 1 ELSE 0 END) AS Yellow, MAX(CASE WHEN ColorCode = 2 THEN 1 ELSE 0 END) AS Red , MAX(CASE WHEN ColorCode = 3 THEN 1 ELSE 0 END) AS Blue , MAX(CASE WHEN ColorCode = 4 THEN 1 ELSE 0 END) AS Other FROM Colors GROUP BY ColoredObjectId, ColorOther </code></pre> <p>Output</p> <pre><code>ColoredObjectId ColorOther Yellow Red Blue Other --------------- ---------- ----------- ----------- ----------- ----------- 1 NULL 1 1 0 0 1 purple 0 0 0 1 2 NULL 0 1 1 0 2 orange 0 0 0 1 3 NULL 1 0 1 0 3 green 0 0 0 1 </code></pre> <p>Desired output</p> <pre><code>ColoredObjectId ColorOther Yellow Red Blue Other --------------- ---------- ----------- ----------- ----------- ----------- 1 purple 1 1 0 1 2 orange 0 1 1 1 3 green 1 0 1 1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload