如何将SQL中的列中的值PIVOT到新的列名中,然后列出这些PIVOT列下的其他列值?

时间:2016-06-02 11:40:03

标签: sql group-by pivot

我有一个包含3列的表,其中第一列是标识符,另外两列包含链接到第一列中值的数据,如下所示:

ID |   CutOff   | Value
-------------------------------------
01 | 2016-03-31 | AA
01 | 2016-04-30 | AB
01 | 2016-05-31 | AC
02 | 2016-03-31 | BA
02 | 2016-04-30 | BB
02 | 2016-05-31 | BC
03 | 2016-03-31 | FA
03 | 2016-04-30 | FB
03 | 2016-05-31 | FC

我需要将第一列DISTINCT值PIVOT到列名中,但是将信息保存在相应PIVOTed列下的另外两列(CutOff和Value)中。所有ID的CutOff日期都相同,但Value列中的值对每个ID都是唯一的,这是所需的结果:

CutOff     | 01 | 02 | 03 |
---------------------
2016-03-31 | AA | BA | FA
2016-04-30 | AB | BB | FB
2016-05-31 | AC | BC | FC

我已经Google搜索并拖网StackExchange几个小时没有到达那里,任何人都可以帮助?

3 个答案:

答案 0 :(得分:0)

您可以使用条件聚合执行此操作:

parseXmlFile

这是ANSI标准语法,并且受任何数据库支持。

答案 1 :(得分:0)

如果select CutOff, max(case when od = '01' then Value end) as [01], max(case when od = '02' then Value end) as [02], max(case when od = '03' then Value end) as [03] from tablename group by CutOff 有限,您可以尝试使用条件聚合:

SQL Server

对于PIVOT,您可以使用原生select CutOff, [01], [02], [03] from tablename pivot(max(value) for id in([01], [02], [03])) p 声明:

let googlespreadsheet = require('google-spreadsheet');

答案 2 :(得分:0)

感谢您的帮助,我终于找到了一种适用于SE的类似主题的方法:

public sealed class FlattenedCircularTree<T>
{
    private readonly T _root;
    private readonly Func<T, IEnumerable<T>> _getChildren;
    private readonly HashSet<T> _visited = new HashSet<T>();
    private readonly List<T> _nodes = new List<T>();

    public FlattenedCircularTree(T root, Func<T, IEnumerable<T>> getChildren)
    {
        _root = root;
        _getChildren = getChildren;
    }

    public IEnumerable<T> AllNodes()
    {
        FindNodes(_root);
        return _nodes;
    }

    private void FindNodes(T current)
    {
        if (!_visited.Add(current))
            return;
        _nodes.Add(current);
        IEnumerable<T> children = _getChildren(current);
        if (children != null)
            foreach (T child in children)
                FindNodes(child);
    }
}
相关问题