在Oracle sql中,我希望通过删除空列来对行进行分类

时间:2017-05-14 13:35:43

标签: sql oracle

例如, 我的表格给出了以下值,

  | AppID | Sales           | Salaries     |  Bills   |
  +-------+-----------------+--------------+----------+
  | 7     |54               | Null         |  Null    |
  | 7     |Null             | 66           |  Null    |
  | 7     |Null             | Null         | 88       |
  | 8     |Null             | 7654         | Null     |
  | 8     |Null             | Null         | 72       |
  | 8     |Null             | Null         | 78       | 

我如何得到结果为()

 | AppID | Sales           | Salaries     |  Bills   |
  +-------+-----------------+-------------+----------+
  | 7     |54              | 66           |  88      |
  | 8     |Null            | 7654         |  72      |
  | 8     |Null            | Null         | 78       |

- 为Appid 8添加了重复值 ?

等待回答。

2 个答案:

答案 0 :(得分:1)

您可以使用聚合。

Max

select appId, 
    max(sales) as sales,
    max(Salaries) as salaries,
    max(Bills) as bills
from your_table
group by appId;

Sum

select appId,
    sum(sales) as sales,
    sum(Salaries) as salaries,
    sum(Bills) as bills
from your_table
group by appId;

答案 1 :(得分:0)

Oracle安装程序

CREATE TABLE my_table( AppID, Sales, Salaries, Bills ) AS
  SELECT 7, 54, NULL, NULL FROM DUAL UNION ALL
  SELECT 7, NULL, 66, NULL FROM DUAL UNION ALL
  SELECT 7, NULL, NULL, 88 FROM DUAL UNION ALL
  SELECT 8, NULL, 7654, NULL FROM DUAL UNION ALL
  SELECT 8, NULL, NULL, 72 FROM DUAL UNION ALL
  SELECT 8, NULL, NULL, 78 FROM DUAL;

<强>查询

SELECT AppId,
       Sales,
       Salaries,
       Bills
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY AppId, Column_Name ORDER BY ROWNUM ) rn
  FROM   my_table
  UNPIVOT (value FOR column_name IN (Sales, Salaries, Bills) ) t
)
PIVOT
(
   MAX( value )
   FOR column_name IN (
    'SALES' AS sales, 'SALARIES' AS salaries, 'BILLS' AS bills
   )
)
ORDER BY AppId, rn;

<强>输出

APPID SALES SALARIES BILLS
----- ----- -------- -----
    7    54       66    88
    8           7654    72
    8                   78