3

我有以下表结构:

ID       COMPANY       PROJECT      ACTIVITY     TYPE
1        A             1            A1.1         NORMAL
2        A             1            A1.2         NORMAL
3        A             1            A1.3         NORMAL
4        A             2            A2.1         DUMMY
5        A             2            A2.2         DUMMY
6        A             2            A2.3         DUMMY
7        A             3            A3.1         NORMAL
8        A             3            A3.2         DUMMY
9        A             3            A3.3         NORMAL

我的目标是检索所有活动(在组合公司 x 项目内)都是虚拟的公司和项目。

我写了下面的SQL:

SELECT COMPANY, PROJECT
FROM TABLE
GROUP BY COMPANY, PROJECT
HAVING TYPE = 'DUMMY'

但是它不仅带来了 Company A 和 Project 2(这是唯一满足我条件的),还带来了 Company 3 Project 3(只有一个 DUMMY 类型)。

你们能帮我修正一下声明吗?

谢谢!!!!

4

2 回答 2

3

你离成功很近了。利用MAXMIN功能。

SELECT  COMPANY, PROJECT
FROM    TABLE
GROUP   BY COMPANY, PROJECT
HAVING  MAX(TYPE) = MIN(TYPE) AND
        MAX(TYPE) = 'DUMMY'
于 2013-03-08T15:17:20.530 回答
0

You can use an EXISTS statement to get the answer you're looking for:

SELECT DISTINCT COMPANY, PROJECT
FROM TABLE t
WHERE EXISTS (
  SELECT 1
  FROM TABLE tDummy
  WHERE tDummy.COMPANY = t.COMPANY
  AND tDummy.PROJECT = t.PROJECT
  AND tDummy.[TYPE] = 'DUMMY')
AND NOT EXISTS (
  SELECT 1
  FROM TABLE tNotDummy
  WHERE tNotDummy.COMPANY = t.COMPANY
  AND tNotDummy.PROJECT = t.PROJECT
  AND (
    tNotDummy.[TYPE] <> 'Dummy'
    OR tNotDummy.[TYPE] IS NULL));

This assumes that if TYPE is null, you don't count it as 'DUMMY'.

于 2013-03-08T15:55:06.277 回答