0

给定一个表,t

a     b    c     d      e
1     2    3      4     7   
1     2    3      5     7
3     2    4      6     7
3     2    4      6     8

什么 SQL 查询可以识别具有与列ab中的每个元组关联的一个或多个不同值的实例的列?

在上面的表t中,列de将满足此标准,但不满足列c

对于来自列ab的元组 <1,2> 和 <3,2> ,列c对于每个元组没有不同的值。

d列有一个元组 <1,2> 值变化的实例——值 4 和 5。

e列也有一个元组 <3,2> 值变化的实例——值 7 和 8。

4

2 回答 2

2

Something like this should work for you using CASE, COUNT and GROUP BY:

select 
  a, b,
  case when count(distinct c) > 1 then 'yes' else 'no' end colc,
  case when count(distinct d) > 1 then 'yes' else 'no' end cold,
  case when count(distinct e) > 1 then 'yes' else 'no' end cole
from t
group by a, b

SQL Fiddle Demo

于 2013-02-24T00:54:30.563 回答
0

Slightly indirectly:

SELECT a, b,
       COUNT(DISTINCT c) AS num_c,
       COUNT(DISTINCT d) AS num_d,
       COUNT(DISTINCT e) AS num_e
  FROM t
 GROUP BY a, b;

This yields:

1   2   1   2   1
3   2   1   1   2

If the num_c or num_d or num_e column has a value greater than 1, then there are varying values. You can vary the query to list whether the column is varying for a given value of (a, b) by using a CASE statement like this:

-- v for varying, n for non-varying
SELECT a, b,
       CASE WHEN COUNT(DISTINCT C) > 1 THEN 'v' ELSE 'n' END AS num_c,
       CASE WHEN COUNT(DISTINCT d) > 1 THEN 'v' ELSE 'n' END AS num_d,
       CASE WHEN COUNT(DISTINCT e) > 1 THEN 'v' ELSE 'n' END AS num_e
  FROM t
 GROUP BY a, b;

This yields:

1   2   n   v   n
3   2   n   n   v

If you really want just to know whether any set of values in the given column varies for any values of (a, b) — and not which values of (a, b) it varies for — you can use the query above as a sub-query in the FROM clause and organize things as you want.

SELECT MAX(num_c) AS num_c,
       MAX(num_d) AS num_d,
       MAX(num_e) AS num_e
  FROM (SELECT a, b,
               CASE WHEN COUNT(DISTINCT C) > 1 THEN 'v' ELSE 'n' END AS num_c,
               CASE WHEN COUNT(DISTINCT d) > 1 THEN 'v' ELSE 'n' END AS num_d,
               CASE WHEN COUNT(DISTINCT e) > 1 THEN 'v' ELSE 'n' END AS num_e
          FROM t
         GROUP BY a, b
       );

This relies on v being larger than n; it is easy enough (and convenient enough) for this binary decision, but not necessarily convenient or easy if there are, say, 4 states to map.

This yields:

n   v   v
于 2013-02-24T00:55:49.200 回答