1

I am trying to figure out how to pivot column to row without aggregation.

I have a table with Account, Company Name and Company %. I am trying to pivot so that all companies info with respect to that account are on the same row. There isn't a limit on how many companies an account could have and I will need to include all companies.

Currently:

Account Company Name Company %
1 Company A Company A%
1 Company B Company B%
2 Company B Company B%
3 Company A Company A%
3 Company B Company B%
3 Company K Company K%
3 Company W Company W%

Expected Results:

Account Company 1 Company 1% Company 2 Company 2% Company 3 Company 3% Company 4 Company 4%
1 Company A Company A% Company B Company B%
2 Company B Company B%
3 Company A Company A% Company B Company B% Company K Company K% Company W Company W%
10
  • 1
    In HTML? SQL? What is the question? Commented Jun 21, 2021 at 17:54
  • Pivot in SQL. Thanks Commented Jun 21, 2021 at 18:05
  • 1
    Which DBMS? e.g. Microsoft SQL Server, MySQL, Oracle Commented Jun 21, 2021 at 18:26
  • Also, does it need to be a true pivot with actual columns, or would something like listagg be acceptable? e.g. 2, "Company B, Company B%" Commented Jun 21, 2021 at 18:29
  • Just curious what's wrong with aggregation? Commented Jun 21, 2021 at 18:41

1 Answer 1

2

Any modern implementation of SQL has ROW_NUMBER() and that can be used for what you want.

It still uses MAX() to collapse multiple rows in to single rows, but it is being used as pick the one value that isn't NULL.

There is no sane reason to avoid its use.

WITH
  sorted AS
(
  SELECT
    yourTable.*,
    ROW_NUMBER() OVER (PARTITION BY account ORDER BY company_name)  AS account_row_id
  FROM
    yourTable
)
SELECT
  account,
  MAX(CASE WHEN account_row_id = 1 THEN company_name END)   AS company_name_1,
  MAX(CASE WHEN account_row_id = 1 THEN company_pct  END)   AS company_pct_1,

  MAX(CASE WHEN account_row_id = 2 THEN company_name END)   AS company_name_2,
  MAX(CASE WHEN account_row_id = 2 THEN company_pct  END)   AS company_pct_2,

  MAX(CASE WHEN account_row_id = 3 THEN company_name END)   AS company_name_3,
  MAX(CASE WHEN account_row_id = 3 THEN company_pct  END)   AS company_pct_3,

  MAX(CASE WHEN account_row_id = 4 THEN company_name END)   AS company_name_4,
  MAX(CASE WHEN account_row_id = 4 THEN company_pct  END)   AS company_pct_4
FROM
  sorted
GROUP BY
  account
ORDER BY
  account
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, it took me a long time to test this but it worked. Thank you so much! I tried to upvote but it said i need 15 reputation points. Also how do i accept this as the answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.