在SQL中获取列值的组合

时间:2012-08-27 15:49:21

标签: tsql

我有这样的数据库结构

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 )

答案 2 :(得分:0)

以下内容可视为@Abe Miessler's建议的发展:

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()聚合函数的windowing版本来避免加入。

顺便说一句,如果您需要使查询更具通用性并且返回任何具有多个不同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),并返回最小值与最大值不同的组。 / p>