0

我有一个这样的数据库结构

rowid   deltaValue  Applicable
1        r            n/d
1        w            n/d
1        m            n/d
2        r            n/d
2        w            n/d
2        m            n/d
3        r            n/d
3        w            n/r
3        m            n/d

所以基本上我只想选择最后一组'rowid',即rowid=3。这是因为它是唯一一个组合了n/d, n/r

是否有一个 tsql 查询将只查看组合并拉取组(即 rowid)。这是我到目前为止所拥有的:

select  *
from table
where 1=1
and deltaValue in ('r','w','m')
and ((   1=(case when [DeltaValue] = 'r' and [Applicable]='n/r' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'w' and [Applicable]='n/d' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'm' and [Applicable]='n/d' then 1 else 0 end)
     ) OR
     (   1=(case when [DeltaValue] = 'r' and [Applicable]='n/d' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'w' and [Applicable]='n/r' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'm' and [Applicable]='n/d' then 1 else 0 end)
     ) OR
     (   1=(case when [DeltaValue] = 'r' and [Applicable]='n/d' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'w' and [Applicable]='n/d' then 1 else 0 end)
     and 1=(case when [DeltaValue] = 'm' and [Applicable]='n/r' then 1 else 0 end)
     )
    )

输出:

3        r            n/d
3        w            n/r
3        m            n/d
4

3 回答 3

1

试试这个:

with temp as
(
    SELECT t.rowid
    FROM myTable t
    GROUP BY t.rowid
    HAVING COUNT(CASE WHEN Applicable= 'n/d' THEN 1 END) > 0
       AND COUNT(CASE WHEN Applicable= 'n/r' THEN 1 END) > 0;
)
select * from MyTable as mt
INNER JOIN temp as t
ON mt.RowId = t.RowId
于 2012-08-27T16:07:29.713 回答
0

请试试这个

SELECT      *
FROM        Table1
WHERE       rowid IN ( SELECT rowid
                       FROM   ( SELECT * , DENSE_RANK () OVER (PARTITION BY rowid ORDER     BY Applicable) AS myRank FROM Table1
                              ) AS t
                       WHERE  t.myRank > 1 )
于 2012-08-27T16:16:04.297 回答
0

以下可以被认为是@Abe Miessler建议的发展:

WITH counted AS (
  SELECT
    *,
    [n/d count] = COUNT(CASE DeltaValue WHEN 'n/d' THEN 1 END) OVER (PARTITION BY rowid),
    [n/r count] = COUNT(CASE DeltaValue WHEN 'n/r' THEN 1 END) OVER (PARTITION BY rowid)
  FROM atable
)
SELECT
  rowid,
  DeltaValue,
  Applicable
FROM counted
WHERE [n/d count] > 0 AND [n/r count] > 0
;

如您所见,您可以通过使用聚合函数的窗口版本来避免连接。COUNT()

顺便说一句,如果您需要使查询更加通用并且返回具有多个 distinct 的任何组DeltaValue,您可以使用稍微不同的方法:

WITH counted AS (
  SELECT
    *,
    MinDeltaValue = MIN(DeltaValue) OVER (PARTITION BY rowid),
    MaxDeltaValue = MAX(DeltaValue) OVER (PARTITION BY rowid)
  FROM atable
)
SELECT
  rowid,
  DeltaValue,
  Applicable
FROM counted
WHERE MinDeltaValue <> MaxDeltaValue
;

上面的查询使用窗口化MAX()MIN()找到每组(的rowid)的最小值和最大值,并返回最小值与最大值不同的那些组。

于 2012-08-28T20:47:00.943 回答