SQL select指令从现有表创建新表

时间:2014-02-03 14:01:21

标签: sql pivot

我正在寻找一条sql指令(Select)来从现有表格创建表格格式。

我有这种格式的表格。

Id|Record|Title  |Value|

 1. |1   |name   |John |
 2. |1   |ammount|200  |
 3. |2   |name   |Lisa |
 4. |2   |ammount|400  |

但是我需要以这种格式显示信息

Record|Name|Ammount|

 1.   |John|    200|
 2.   |Lisa|    400|

我不想创建新表,我正在寻找选择或连接操作。 你知道任何执行此操作的指令吗? 提前谢谢。

3 个答案:

答案 0 :(得分:3)

SELECT record, 
       MAX(CASE WHEN Title = 'name' THEN Value END) AS Name,
       MAX(CASE WHEN Title = 'ammount' THEN Value END) AS Ammount
FROM YourTable
GROUP BY record

SQLFIDDLE

答案 1 :(得分:1)

你可以尝试这个(假设它是MySQL):

SELECT
    A.Record,
    A.Value AS Name,
    B.Value AS Ammount
FROM
    tbl A
JOIN
    tbl B
ON
    A.Record = B.Record
WHERE
    A.Title = 'name' AND
    B.Title = 'ammount'

基本上,你通过记录值两次加入同一个表,按标题列过滤结果并选择所需的列。

SQLfiddle示例

答案 2 :(得分:-1)

SELECT tt.record,
      (SELECT value FROM t WHERE tt.record = record AND title = 'name') AS name,
      (SELECT value FROM t WHERE tt.record = record AND title = 'ammount') AS ammount
  FROM t as tt
  GROUP BY tt.record
  ;