Similar to rows-to-col(EAV to relational) - SQL query please

落爺英雄遲暮 提交于 2019-12-12 03:04:08

问题


My dataset is not exactly like EAV format, but it's somewhat similar; here's the data:

In the format I need is as follows:

For every EN_NO group I need the data in above format. If group on EN_NO > 1 then respestive product key should go to respestive product column otherwise not (for e.g. EN_NO 4 and 5).

I hope I am clear. Data is in a Qracle table, please suggest a query to get the data in the format I need.

Thanks, Prakash


回答1:


I would highly recommend altering your table structure. At present you have two pieces of information tied into a single field. This is a SQL Anti-Pattern and destroys the ability of Oracle to user certain optimisations.

Instead, please consider splitting "PROD_KEY" into two fields (PRODUCT_TYPE = Prod_A, etc) (SUB_PRODUCT_ID = 1, 2, 3, etc). Or, to cause less potential change across the database, simply add the PRODUCT_TYPE to your current table.


That said, using your current structure...

SELECT
  EN_NO,
  PROD_KEY,
  CASE WHEN (EN_NO < 4) AND (LEFT(PROD_KEY, 6) = 'Prod_A') THEN PROD_KEY ELSE NULL END AS Prod_A,
  CASE WHEN (EN_NO < 4) AND (LEFT(PROD_KEY, 6) = 'Prod_B') THEN PROD_KEY ELSE NULL END AS Prod_B,
  CASE WHEN (EN_NO < 4) AND (LEFT(PROD_KEY, 6) = 'Prod_C') THEN PROD_KEY ELSE NULL END AS Prod_C,
  PROD_QTY
FROM
  yourTable

This works when you know specifically what columns you need as output. If you need the code to adapt to having Prod_D, etc, then you need to write code that writes code (Dynamic SQL).




回答2:


What you're showing is a pivot table. If you want a query that will automatically add columns corresponding to the distinct data values in your table, then you're out of luck. SQL does not support this; columns must be known and fixed at the time you prepare the query -- before it reads any data values in the table.

To do this, you need to get a list of distinct prod_key values (or the substring up to the : character):

SELECT DISTINCT LEFT(PROD_KEY, 6) FROM yourTable;

And then write application code to turn this list of values into a series of column expressions in a dynamic SQL statement, as @Dems mentions.

The other option is to fetch the raw data as it exists in the table, then write application code that iterates over it and groups it into a tabular report one data value at a time.

Either way, you need to write application code unless you already know the list of distinct prod_key types you want to fetch.



来源:https://stackoverflow.com/questions/8516710/similar-to-rows-to-coleav-to-relational-sql-query-please

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!