N
N
NeoZeed2014-05-13 09:09:33
SQL
NeoZeed, 2014-05-13 09:09:33

How to make columns from repeating rows using SQL query?

Hello! Let's say there is a table
Date | Products | Quantity
------------------------------------------------
19.03 .2014 | "Bran" | 24211 03/19/2014
| "Feathers" | 0
March 19, 2014 | "Millet" | 150
03/20/2014 | "Carton" | 165
03/20/2014 | "Brick" | 70
March 20, 2014 | "Bran" | 91
March 20, 2014 | "Feathers" | 0
03/20/2014 | "Millet" | 50
March 21, 2014 | "Brick" | 140
03/21/2014 | "Bran" | 34137
03/21/2014 | "Feathers" | 0
How to make it
"Bran" | "Feathers" | "Millet" | "Carton" | "Brick
-------------------------------------------------- --------------------------------------------
03/19/2014 | 24211 | 0 | 150 | 0 | 0
03/20/2014 | 91 | 0 | 50 | 165 | 70
March 21, 2014 | 34137 | 0 | 0 | 0 | 140
SQL query or SQLDataReader in C++ windows Forms

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
svd71, 2014-05-13
@NeoZeed

select
m.date,
(select sum(kolichestvo) from mytable p where p.produkt='Отруби' and p.date=m.date) as OTRUBI,
(select sum(kolichestvo) from mytable p where p.produkt='Перья' and p.date=m.date) as PERIA,
(select sum(kolichestvo) from mytable p where p.produkt='Пшено' and p.date=m.date) as PSHENO,
(select sum(kolichestvo) from mytable p where p.produkt='Картон' and p.date=m.date) as Karton,
(select sum(kolichestvo) from mytable p where p.produkt='Кирпич' and p.date=m.date) as KIRPICH

from mytable m
group by m.date
order by m.date

A
Alexey Skahin, 2014-05-13
@pihel

For sqlite like this:

SELECT Дата ,
 SUM(CASE WHEN  Продукция = 'Отруби' THEN  количество END ) as otrubi,
 SUM(CASE WHEN  Продукция = 'Перья' THEN  количество END ) as peria,
 .....
FROM таблица
GROUP BY Дата

For mssql/oracle, if there are many entities, PIVOT can be used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question