PIVOT超过两列

时间:2015-10-20 19:10:47

标签: sql sql-server pivot

是否有一种更优雅的方式在下表中实现PIVOT - 基本上我试图计算任何用户ID的typeid,以及获取每种类型的第一个值并转动类型和值(使用sql server 2012):

enter image description here

这是预期的结果:

enter image description here

这就是我想出的:

func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {

    switch (lhs, rhs) {
    case let (l?, r?) : // shortcut for (.Some(l), .Some(r))
        return l == r
    case (.None, .None):
        return true
    default:
        return false
    }
}

表架构:

SELECT  userid ,
        MAX([1]) [1] ,
        MAX([2]) [2] ,
        MAX(value1) [value1] ,
        MAX(value2) [value2]
FROM    ( SELECT    userid ,
                    typeid ,
                    FIRST_VALUE(value) OVER ( PARTITION BY userid, typeid ORDER BY testid ) [value] ,
                    'value' + CONVERT(VARCHAR(20), typeid) [valuepivot]
          FROM      dbo.test
        ) t PIVOT( COUNT(typeid) FOR typeid IN ( [1], [2] ) ) as pivottype
        PIVOT( MAX(value) FOR [valuepivot] IN ( [value1], [value2] ) ) as pivottype2
GROUP BY userid

1 个答案:

答案 0 :(得分:0)

我会使用条件聚合来做到这一点:

Using Ionic.Zip;
public static void ZipJpeg(int ID)
{
    ZipFile zip = new ZipFile();
    Dictionary<int, byte[]> photos = new Dictionary<int, byte[]>();
    photos = clientInfo_BL.GetByID(ID);
    string fileName;
    foreach(var p in photos.Values)
    {
        fileName = p.uploadDate.toString() + ".jpeg";
        using(Image image = image.FromStream(new MemoryStream(p.ImageData)))
        {
             image.Save(fileName. ImageFormat.Jpeg);
        }
        Zip.AddEntry(image); // couldnt figure out this one
    }
    zip.save()//not sure if this one is right
    return zip;
}

是否更简单是一个意见问题。