简体   繁体   中英

SQL: How to select multiple values from one table as seperate columns

I'm writing a C# WinForm Application, the data is displayed in a DataGridView.

Example of table

ITEMNO|VALUE|OPTFIELD
Item 1|A|LOCATION
Item 1|25|STOCKQTY
Item 2|B|LOCATION
Item 2|10|STOCKQTY

What I currently display in the DGV

PARTNUMBER | LOCATION
Item 1 | A

What I want to display

PARTNUMBER|LOCATION|STOCKQTY
Item 1 | A | 25

I was thinking of amending the Query as;

SELECT ITEMNO, VALUE, OPTFIELD, OPTFIELD AS STOCKQTY
FROM ICITEMO
WHERE ITEMNO = 'Item 1' and OPTFIELD LIKE 'LOCATION1' and OPTFIELD LIKE 'STOCKQTY'

But this returns no results

As the data is contained in one column, how do I display the separate values in separate columns, despite coming from one column?

You can use simple pivot as below:

select * from #youritem
pivot (max(value) for optfield in ([LOCATION],[STOCKQTY])) p

Your output:

+--------+----------+----------+
| itemno | LOCATION | STOCKQTY |
+--------+----------+----------+
| Item 1 | A        |       25 |
| Item 2 | B        |       10 |
+--------+----------+----------+

Your input table:

create table #youritem (itemno varchar(10), value varchar(5), optfield varchar(20))

insert into #youritem
(ITEMNO,VALUE, OPTFIELD ) VALUES
 ('Item 1','A ','LOCATION')
,('Item 1','25','STOCKQTY')
,('Item 2','B ','LOCATION')
,('Item 2','10','STOCKQTY')

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