嗨,我想知道这在T-SQL中是否可行。
如果第2行和第3行/第5行和第6行的组合存在,那么想法是“不”返回第1行和第4行等行。
declare @table table
(
A int,
B char(2),
C char(2),
D char(2)
)
insert into @table
select 2, 'A1', 'B1', NULL -- row 1
union
select 2, 'A1', 'B1', 'C1' -- row 2 and row 3 is a combination (values are equal)
union
select 3, 'A1', 'B1', 'C1'
union
select 2, 'A2', 'B2', NULL -- row 4
union
select 2, 'A2', 'B2', 'C2' -- row 5 and row 6 is a combination (values are equal)
union
select 3, 'A2', 'B2', 'C2'
任何想要参加此活动的人? 谢谢 最好的祝福 史蒂夫
答案 0 :(得分:2)
试试这个
SELECT DISTINCT A,B,C,D FROM @table
WHERE
A IS NOT NULL AND
B IS NOT NULL AND
C IS NOT NULL AND
D IS NOT NULL
OR
SELECT DISTINCT A,B,C,D FROM @table
WHERE
D IS NOT NULL
答案 1 :(得分:2)
这样的事情?
declare @table table
(
ID INT ,
A int,
B char(2),
C char(2),
D char(2)
)
insert into @table
select 1, 2, 'A1', 'B1', NULL -- row 1
union
select 2, 2, 'A1', 'B1', 'C1' -- row 2 and row 3 is a combination (values are equal)
union
select 3, 3, 'A1', 'B1', 'C1'
union
select 4, 2, 'A2', 'B2', NULL -- row 4
union
select 5, 2, 'A2', 'B2', 'C2' -- row 5 and row 6 is a combination (values are equal)
union
select 6, 3, 'A2', 'B2', 'C2'
SELECT *
FROM @table t
WHERE EXISTS(SELECT * FROM @table t1 WHERE t.id IN (t1.id + 1, t1.id + 2)
AND t.d IS NULL )
答案 2 :(得分:2)
NOT EXISTS
是要走的路:
SELECT A,B,C,D from @table t1
WHERE NOT EXISTS(
SELECT 1 FROM @table t2
WHERE t1.A < t2.A
AND COALESCE(t1.B,'')=COALESCE(t2.B,'')
AND COALESCE(t1.C,'')=COALESCE(t2.C,'')
AND COALESCE(t1.D,'')=COALESCE(t2.D,'')
)
COALESCE
- 技巧是比较两个空值。否则null=null
将返回null
,并且将包含具有空值的相等行。
答案 3 :(得分:1)
我认为我们可以通过使用表的聚合和排序单独过滤记录来实现这一点。我相信,你想要消除那些后面跟行组合的行...... 如果是这样,下面可能会有效...
declare @table table
(
A int,
B char(2),
C char(2),
D char(2)
)
insert into @table
select 2, 'A1', 'B1', NULL -- row 1
union
select 2, 'A1', 'B1', 'C1' -- row 2 and row 3 is a combination (values are equal)
union
select 3, 'A1', 'B1', 'C1'
union
select 2, 'A2', 'B2', NULL -- row 4
union
select 2, 'A2', 'B2', 'C2' -- row 5 and row 6 is a combination (values are equal)
union
select 3, 'A2', 'B2', 'C2'
SELECT
T.*
FROM
@table T
INNER JOIN
(
SELECT
T1.*
FROM
(
SELECT
ROW_NUMBER() OVER(ORDER BY B,C,D) As RowNumber,
MIN(A) AS A,
B,
C,
D,
COUNT(1) Cnt
FROM @TABLE
GROUP BY B,C,D
) T1
LEFT JOIN
(
SELECT
ROW_NUMBER() OVER(ORDER BY B,C,D) As RowNumber,
MIN(A) AS A,
B,
C,
D,
COUNT(1) Cnt
FROM @TABLE
GROUP BY B,C,D
) T2 ON T2.RowNumber = T1.RowNumber + 1
WHERE ISNULL(T2.Cnt,0) <= 1
) NonPostDuplicateRows
ON T.B = NonPostDuplicateRows.B
AND T.C = NonPostDuplicateRows.C
AND T.D = NonPostDuplicateRows.D