Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

How to pivot data in SQL

I have data that looks much like this (3 columns of data), unfortunately I can't get it to display properly

NCR NO  LU_NAME           KEY_REF
100001  Project           PROJECT_ID=ID#^
100001  SupplierInfo      SUPPLIER_ID=UNIQUESUPPLIERNUMBER^
100001  PurchaseOrder     ORDER_NO=UNIQUEORDERNO^
100196  PurchaseReceipt   UNIQUE PURCHASE RECEIPT
100511  InventoryPart     CONTRACT=UNIQUECONTRACTNO

What I want is to have one record for each NCR number and a column of data for Project, SupplierInfo, etc, which contains the unique Key_Ref. Let's say the table name is OC. Can someone assist with the code to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This type of data transformation is called a pivot, some database products have a function that can do this for you.

If you are working in a database that does not have a pivot function, then you can use an aggregate function with a CASE expression:

select ncr_no,
  max(case when LU_NAME = 'Project' then KEY_REF end) Project,
  max(case when LU_NAME = 'SupplierInfo' then KEY_REF end) SupplierInfo,
  max(case when LU_NAME = 'PurchaseOrder' then KEY_REF end) PurchaseOrder,
  max(case when LU_NAME = 'PurchaseReceipt' then KEY_REF end) PurchaseReceipt,
  max(case when LU_NAME = 'InventoryPart' then KEY_REF end) InventoryPart
from yourtable
group by ncr_no

See SQL Fiddle with Demo.

The above will work great with a known number or finite number of LU_NAME values, if you will have an unknown number then you will need to implement dynamic SQL but that code will vary depending on your database.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...