基于值的数据透视表和聚合

时间:2018-06-18 14:41:22

标签: mysql sql pivot

<div class="container-fluid">
  <nav class="navbar-expand-lg navbar navbar-light">
    <button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button"><span class="navbar-toggler-icon"></span>Menu</button>

    <div class="collapse navbar-collapse justify-content-center" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item active">
          <a class="nav-link" href="about.html">ABOUT</a>
        </li>




        <li class="nav-item">
          <a class="nav-link" href="Contact.html">CONTACT</a>
        </li>


        <li class="nav-item active">
          <a class="btn btn-outline-primary" href="https://spartan-safety-limited.gogecko.com/users/login">TRADE ACCOUNT</a>
        </li>
      </ul>
    </div>
  </nav>
</div>
<!--CAROUSEL-->

有没有办法使用mysql将表聚合到这个?

+-----------------+------------+---
|  A          | B          | C    |
+-----------------+------------+---
|  a1         | NULL       | NULL |
|  a2         | NULL       | NULL |
|  NULL       | b1         | NULL |
|  NULL       | b2         | NULL |
|  NULL       | b3         | NULL |
|  NULL       | NULL       | c1   |
+-----------------+------------+---

但是,行数取决于列中非空值,其中具有最大数量的非空值,其余列将跟随。是否有查询来制作这样的东西? PS:这是通过旋转文本值。

1 个答案:

答案 0 :(得分:1)

这不是一个支点。您正在尝试将事物列表放入列中。这不是一件非常SQL好的事情,但您可以使用变量(或MySQL 8 +中的row_number())来完成它:

select rn, max(a) as a, max(b) as b, max(c) as c
from ((select (@rna := @rna + 1) as rn, a, null as b, null as c
       from t cross join
            (select @rna := 0) params
       where a is not null
      ) union all
      (select (@rnb := @rnb + 1) as rn, null, b, null
       from t cross join
            (select @rnb := 0) params
       where b is not null
      ) union all
      (select (@rnc := @rnc + 1) as rn, null, null, c
       from t cross join
            (select @rnc := 0) params
       where c is not null
      )
     ) t
group by rn
order by rn;