如何通过ObjectId对表进行分组?

时间:2016-09-08 08:16:45

标签: sql-server tsql group-by

我对SQL很熟悉。

我使用的是Sql Server 2012。

我有这张桌子:

 peerID = MCPeerID(displayName: UIDevice.current.name)

我需要通过ObjectId来扩展表,如果在grupped表中至少有一行具有属性false,则它必须为False。

这里是所需的分组表:

 2016-09-08 10:13:43.016600 PeerCodeATV[208:51135] [ViceroyTrace] [ICE][ERROR] ICEStopConnectivityCheck() found no ICE check with call id (847172408)
 2016-09-08 10:13:47.577645 PeerCodeATV[208:51155] [GCKSession] SSLHandshake returned with error [-9819].

IsNormal列是BIT类型。

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

WITH Src AS
(
    SELECT * FROM (VALUES
    (3379, 5, CAST(1 AS bit), '2016-09-08 00:00:00.000', 1019, 1, 16),
    (3380, 5, CAST(1 AS bit), '2016-09-08 00:00:00.000', 1019, 1, 20),
    (3381, 5, CAST(0 AS bit), '2016-09-08 00:00:00.000', 1020, 1, 16),
    (3382, 5, CAST(1 AS bit), '2016-09-08 00:00:00.000', 1020, 1, 54)
    ) T(Id, SiteId, IsNormal, DateReview, ObjectId, FrequencyId, InspectionId)
)
SELECT Id, SiteId, IsNormal, DateReview, ObjectId, FrequencyId, InspectionId
FROM
(
    SELECT ObjectId, MIN(SiteId) SiteId,
        CONVERT(bit, MIN(CONVERT(int, IsNormal))) IsNormal,
        MIN(DateReview) DateReview, MIN(FrequencyId) FrequencyId
    FROM Src
    GROUP BY ObjectId
) Dist
CROSS APPLY
(
    SELECT STUFF((SELECT ','+CONVERT(varchar(10),Id)
    FROM Src
    WHERE ObjectId=Dist.ObjectId
    FOR XML PATH('')), 1, 1, '')
) Ids(Id)
CROSS APPLY
(
    SELECT STUFF((SELECT ','+CONVERT(varchar(10),InspectionId)
    FROM Src
    WHERE ObjectId=Dist.ObjectId
    FOR XML PATH('')), 1, 1, '')
) InspectionIds(InspectionId)

答案 1 :(得分:1)

试试这个,

class D