如何比较不同行中的相同列?

时间:2017-11-15 08:24:30

标签: oracle pivot-table

我提取了如下数据

Name   Session     CATEGORY   HT     WT     BMI
John   SESSION 1   OW         1.5    64.6   28.71
John   SESSION 3   OW         1.52   63.2   27.35
Eric   SESSION 1   OW         1.48   55.7   25.43
Eric   SESSION 3   OW         1.52   55.4   23.98

我希望以下面的格式

Name  session_1_Category  Session_1_height  session_1_weight  session_1_BMI  session_3_Category  Session_3_height  session_3_weight  session_3_BMI
John  OW                  1.5               64.6              28.71          OW                  1.52              63.2              27.35
Eric  OW                  1.48              55.7              25.43          OW                  1.52              55.4              23.98

我正在使用oracle数据库。请帮助我使用SQL查询以上述格式提取数据。

2 个答案:

答案 0 :(得分:2)

在Oracle中,您可以使用PIVOT

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE TABLE_NAME ( Name, "Session", CATEGORY, HT, WT, BMI ) AS
SELECT 'John', 'SESSION 1', 'OW', 1.5,  64.6, 28.71 FROM DUAL UNION ALL
SELECT 'John', 'SESSION 3', 'OW', 1.52, 63.2, 27.35 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 1', 'OW', 1.48, 55.7, 25.43 FROM DUAL UNION ALL
SELECT 'Eric', 'SESSION 3', 'OW', 1.52, 55.4, 23.98 FROM DUAL;

查询1

SELECT *
FROM   table_name
PIVOT(
  MAX( HT ) AS height,
  MAX( WT ) AS weight,
  MAX( BMI ) AS BMI
  FOR "Session" IN (
    'SESSION 1' AS Session_1,
    'SESSION 3' AS Session_3
  )
)

<强> Results

| NAME | CATEGORY | SESSION_1_HEIGHT | SESSION_1_WEIGHT | SESSION_1_BMI | SESSION_3_HEIGHT | SESSION_3_WEIGHT | SESSION_3_BMI |
|------|----------|------------------|------------------|---------------|------------------|------------------|---------------|
| John |       OW |              1.5 |             64.6 |         28.71 |             1.52 |             63.2 |         27.35 |
| Eric |       OW |             1.48 |             55.7 |         25.43 |             1.52 |             55.4 |         23.98 |

答案 1 :(得分:0)

这是另一种不使用PIVOT表的解决方案,可以跨平台工作 -

SELECT NAME
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN CATEGORY END) AS session_1_Category
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS Session_1_height
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_weight
      ,MAX(CASE WHEN Session = 'SESSION 1' THEN HT END) AS session_1_BMI
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_Category
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS Session_3_height
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_weight
      ,MAX(CASE WHEN Session = 'SESSION 3' THEN HT END) AS session_3_BMI
FROM YOUR_TABLE
GROUP BY NAME