我有一个表格如下:
ItemNumber -- Description -- 31.03.2015 -- 31.04.2015 -- 31.05.2015 -- 31.06.2015
========= -- ======== -- ======== -- ======== -- ======== -- =========
001 ..................xyz..................null................1000...............null................null
002 ..................xya..................2000................null...............3000................null
003 ..................xyb..................null................4000...............null................5000
004 ..................xyc..................6000................7000...............null................null
005 ..................xyd..................null................8000...............9000................null
006 ..................xye..................null................10000...............null................null
===================================================================
如何编写一个查询来返回值,以便可以获得具有值(不为空)的字段的列标题,并获取该列标题,例如:
ItemNumber -- Description -- Quantity -- Date
========= -- ======== -- ====== -- ====
001.............. -- xyz........... -- 1000...... -- 04/31/2015 12:00:00 AM
002.............. -- xya........... -- 2000...... -- 03/31/2015 12:00:00 AM
002.............. -- xya........... -- 3000...... -- 05/31/2015 12:00:00 AM
003.............. -- xyb........... -- 4000...... -- 04/31/2015 12:00:00 AM
诸如此类...
抱歉,格式很糟糕,我不知道如何在没有点的情况下创建正确的间距。
最佳答案
您可以使用大量union all
来做到这一点:
select t.*
from (select ItemNumber, Description, '31.03.2015' as date, `31.03.2015` as quantity
from table
union all
select ItemNumber, Description, '31.04.2015' as date, `31.04.2015` as quantity
from table
. . .
) t
where quantity is not null;
在 Oracle 中,您可以使用双引号而不是反引号来转义列名。
而且,如果您有大量数据,还有其他方式来表达查询,因此您只需扫描一次表。
关于mysql - 选择表列标题作为值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31860198/