-2

I have a table

date product count
1-1-2003 1 100
1-1-2003 2 200

and I must have on exit:

date product1 product2
1-1-2003 100 200

what kind of sql query can arrange it?

I have nothing to try

Tushar
  • 3,527
  • 9
  • 27
  • 49
  • Does this answer your question? [Efficiently convert rows to columns in sql server](https://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns-in-sql-server) – Filburt Mar 23 '23 at 17:17

3 Answers3

1

Here you are trying to pivot product column. This should be possible with simple case expression as :

SELECT
  date,
  SUM(CASE WHEN product = 1 THEN count ELSE 0 END) AS product1,
  SUM(CASE WHEN product = 2 THEN count ELSE 0 END) AS product2
FROM myTable
GROUP BY date;
Tushar
  • 3,527
  • 9
  • 27
  • 49
1

You can use a SQL query with conditional aggregation. Here's a sample query using the CASE statement and GROUP BY clause to pivot the table:

SELECT
  date,
  SUM(CASE WHEN product = 1 THEN count ELSE 0 END) as product1,
  SUM(CASE WHEN product = 2 THEN count ELSE 0 END) as product2
FROM
  some_table
GROUP BY
  date;

You obviously have to replace some_table with the actual name of your table. This query will group the rows by date and create two new columns, product1 and product2, with the respective counts. The CASE statement is used to conditionally sum the count values based on the product number.

matua
  • 597
  • 4
  • 12
0

Without giving you the exact query, a PIVOT in SQL Server would accomplish this.

Zach Lau
  • 45
  • 5