简体   繁体   中英

SQL: query to categorize items

I have table product

area  productname   count
a1     p1            5
a2     p2            6
a1     p2            9
a2     p3            8
a1     p3            1

I want it to be like this; if it is possible in SQL, I'm using SQL Server

a1     count(p1)    count (p2)  count(p3)
a2     count(p1)    count (p2)  count(p3)
.
.
an     count(p1)    count (p2)  count(p3)

For the specific problem you are trying to solve, the following query will work. Evaldas suggested the link that also provides a great example for dynamic pivoting.

select area, p1, p2, p3
from
(select area, productname, counter from test) t
pivot 
(
  min(counter)
  for productname in (p1, p2, p3)
) as piv
order by area;

Example: http://sqlfiddle.com/#!3/2ef59/19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM