如何以下列格式显示数据?

时间:2016-09-08 09:46:01

标签: mysql

我想根据名称明智的新/旧注册列值显示金额值。

当前数据:

Name   | Enrolled| Amount      
------ | ------- | ------     
Deepak |   old   | 200       
bcd    |   New   | 500         
Deepak |   new   | 900         
bcd    |   old   | 300  

预期结果:

Name   |     Enrolled     
------ |   old   | new
Deepak |   200   | 900
bcd    |   300   | 500

2 个答案:

答案 0 :(得分:0)

您可以通过这种方法获得结果:

SELECT A.Name, MAX(A.OldValue) AS Old, MAX(A.NewValue) AS New
FROM (
    SELECT Name, Amount AS OldValue, NULL AS NewValue
    FROM TestTable 
    WHERE Enrolled = 'old'

    UNION 

    SELECT Name, NULL, Amount
    FROM TestTable 
    WHERE Enrolled = 'new'
) A
GROUP BY A.Name 

请找到 Working Demo

答案 1 :(得分:0)

此查询应该:

SELECT 
    names.name Name, olddata.amount Enrolled_Old, newdata.amount Enrolled_New
FROM
    enrol_data olddata
        JOIN
    enrol_data newdata ON (olddata.name = newdata.name)
        JOIN
    (SELECT DISTINCT
        name
    FROM
        enrol_data) names ON (names.name = olddata.name)
WHERE
    LOWER(olddata.Enrolled) = 'old'
        AND LOWER(newdata.Enrolled) = 'new';

<强>输出

+--------+--------------+--------------+
| Name   | Enrolled_Old | Enrolled_New |
+--------+--------------+--------------+
| bcd    |          300 |          500 |
| Deepak |          200 |          900 |
+--------+--------------+--------------+
2 rows in set (0.01 sec)