我有一个看起来像这样的表:
ID | FIELD_NAME | VALUE 23 | sign_up | yes 23 | first_name | Fred 23 | street | Barber Lane 24 | sign_up | no 24 | first_name | Steve 24 | street | Camaro St. 25 | sign_up | yes 25 | first_name | Larry 25 | street | Huckleberry Ave
我想运行一个查询,该查询将选择唯一的ID和值作为命名列,因此它看起来像这样:
ID | SIGN_UP | FIRST_NAME | STREET | 23 | yes | Fred | Barber Lane | 24 | no | Steve | Camaro St. | 25 | yes | Larry | Huckleberry Ave. |
任何帮助将非常感激!!
您可以使用以下简单解决方案:
SELECT DISTINCT a.id, b.value AS SIGN_UP, c.value AS FIRST_NAME, d.value AS STREET FROM tbl a LEFT JOIN tbl b ON a.id = b.id AND b.field_name = 'sign_up' LEFT JOIN tbl c ON a.id = c.id AND c.field_name = 'first_name' LEFT JOIN tbl d ON a.id = d.id AND d.field_name = 'street'
为了安全起见,我创建了join LEFT JOIN,因为我不知道id是否可以包含 缺少的 字段,在这种情况下,它们将显示NULL在我们的派生列中。
LEFT JOIN
NULL
SQL提琴演示