按SQL正确分组

时间:2018-09-24 21:12:58

标签: sql

我有一个表格,用于将名称和值存储在单独的行中,以便在如下所示的位置进行工作。

+--------+------------+--------+------------+----------+
| WorkID | Attribute  | Value  |  Chagedby  |   Date   |
+--------+------------+--------+------------+----------+
|      1 | Unit Name  | Unit 1 | John Smith | Jan-2018 |
|      1 | Unit Value | OK     | John Smith | Jan-2018 |
|      2 | Unit Name  | Unit 2 | John Smith | Feb-2018 |
|      2 | Unit Value | Not Ok | John Smith | Feb-2018 |
|      3 | Unit Name  | Unit 3 | John Smith | Mar-2018 |
|      3 | Unit Value | OK     | John Smith | Mar-2018 |
+--------+------------+--------+------------+----------+

我对此表有一个查询,该查询将其他表联接在一起,并且输出看起来像这样。

+--------+--------------+--------------------+----------------------+------------+----------+
| WorkID |   Location   | Value when unit ID | Value when ok/not ok |  Chagedby  |   Date   |
+--------+--------------+--------------------+----------------------+------------+----------+
|      1 | Springfield  | Unit 1             | NULL                 | John Smith | Jan-2018 |
|      1 | Springfield  | NULL               | OK                   | John Smith | Jan-2018 |
|      2 | Shelbyville  | Unit 2             | NULL                 | John Smith | Feb-2018 |
|      2 | Shelbyville  | NULL               | Not Ok               | John Smith | Feb-2018 |
|      3 | Capital City | Unit 3             | NULL                 | John Smith | Mar-2018 |
|      3 | Capital City | NULL               | OK                   | John Smith | Mar-2018 |
+--------+--------------+--------------------+----------------------+------------+----------+

最终发生的是属性“值”是我单位的名称还是测试结果。我如何将其分组以便它显示在同一行上。

+--------+--------------+--------------------+----------------------+------------+----------+
| WorkID |   Location   | Value when unit ID | Value when ok/not ok |  Chagedby  |   Date   |
+--------+--------------+--------------------+----------------------+------------+----------+
|      1 | Springfield  | Unit 1             | OK                   | John Smith | Jan-2018 |
|      2 | Shelbyville  | Unit 2             | Not OK               | John Smith | Feb-2018 |
|      3 | Capital City | Unit 3             | OK                   | John Smith | Mar-2018 |
+--------+--------------+--------------------+----------------------+------------+----------+

1 个答案:

答案 0 :(得分:0)

我将表连接到自身,按名称过滤一次,按值过滤另一个,如:

select
    a.workid,
    a.value as name,
    v.value as value,
    a.changedby,
    a.date
  from my_table a
  left join my_table v on a.workid = v.workid
  where a.attribute = 'Unit Name'
    and v.attribute = 'Unit Value'

我添加了left join来包含尚无值的属性。