SQL中的垂直分组

时间:2018-03-08 14:04:24

标签: sql sql-server

我有一个包含以下3列的表格。我想分析'AlphaCode'匹配的结果,'Group1'中的所有值在'Group2'中具有相同的值。例如,对于下表,应该划分出1121TA和1161TA的分组,并在输出中获得2807AHQ。

enter image description here

输出应如下所示:

enter image description here

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,那么你有一个可能的解决方案:

USE tempdb
GO
CREATE TABLE t
(
    AlphaCode varchar(50) NOT NULL,
    Group1 int NOT NULL,
    Group2 int NOT NULL
)
GO
INSERT INTO t VALUES
('1121TA', 342, 50285),
('1121TA', 340, 50285),
('1121TA', 341, 50285),
('1121TA', 341, 50345),
('1121TA', 342, 50345),
('1121TA', 340, 50345),
('1161TA', 355, 50347),
('1161TA', 354, 50347),
('1161TA', 354, 50458),
('1161TA', 355, 50458),
('2807AHQ', 77933, 50427),
('2807AHQ', 69939, 51897)
GO


WITH B AS
(
    SELECT 
        t.AlphaCode, t.Group1, t.Group2,
        COUNT(*) OVER (PARTITION BY t.AlphaCode, t.Group2) AS GroupCount
    FROM t
)
SELECT B.AlphaCode, B.Group1, B.Group2
FROM B
WHERE B.GroupCount = 1

GO

另一种解决方案甚至可以在SQL Server 6.5上运行:

SELECT t.AlphaCode, t.Group1, t.Group2
FROM
    t INNER JOIN
    (
        SELECT 
            t.AlphaCode, t.Group2, COUNT(*) AS GroupCount
        FROM 
            t
        GROUP BY
            t.AlphaCode, t.Group2
    ) gc ON t.AlphaCode = gc.AlphaCode AND t.Group2 = gc.Group2
WHERE
    gc.GroupCount = 1

答案 1 :(得分:-1)

通过'雕刻'我相信你的意思是,你想要Group1不重复的记录。 考虑到这一点,您可能希望: 编辑:在所有评论之后,我有点放弃,但这是我的最后一次尝试:

"如果你仔细观察到垂直组与Group1和Group2匹配。"

select * from t1 
      where Group1 in 
            (select Group1 from t1 
                    group by Group1 HAVING COUNT(Group1) <= 1)
      and Group2 in 
            (select Group2 from t1 
                    group by Group2 HAVING COUNT(Group2) <= 1);

&#34; Group1值不得为Group2值&#34;

select * from t1 where Group1 not in (select distinct Group2 from t1)

&#34;选择Group1 / Group2唯一的所有行&#34;

(您可以根据需要将Group1更改为Group2)

select * from t1 group by Group1 HAVING COUNT(Group1) <= 1;

如果你想要&#34; AlphaCode匹配&#34;,你需要问一下你真正想要的东西,因为那是where AlphaCode = "something"

我创造了一个小提琴,可以更容易地重现你所寻找的东西。随意使用它来完成你的帖子

http://sqlfiddle.com/#!9/f75b5d/11