0

我有一个有 2 列我关心的表

Business_ID   /   Product type

我正在尝试编写一个 SQL 查询,以仅获取销售一种类型的企业,而不是其他类型的企业。所以表格填充了

B_ID    prod_type
123  |   A
123  |   A
123  |   B
234  |   A
234  |   C
234  |   C
456  |   A
456  |   D
789  |   A

这样的例子不胜枚举。我正在尝试编写一个 SQL 语句,它将找到一个 B_ID,它销售 prod_type A 而不是 prod_type B、C、D。这是我正在尝试的,但它不起作用

SELECT phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*) 
FROM phop phop_1, phop phop_2
WHERE phop_1.Business_id = phop_2.Business_id
  AND phop_1.PRODUCT_TYPE = 'A'
  AND NOT phop_2.PRODUCT_TYPE = 'B'
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE

我还找到了如何使用外连接排除,但由于它是同一个表,我不能这样做,除非有办法在进行连接之前选择 prod_type A。

select phop_1.Business_id, phop_1.PRODUCT_TYPE, count(*) 
from phop phop_1
LEFT OUTER JOIN phop phop_2
ON phop_1.Business_id = phop_2.Business_id
WHERE phop_2.Business_id IS NULL
GROUP BY phop_1.Business_id, phop_1.PRODUCT_TYPE
4

3 回答 3

4

你可以尝试这样的事情:

SELECT DISTINCT p.BusinessId
FROM phop p
   LEFT JOIN phop p2 ON p.BusinessId = p2.BusinessId AND p2.Product_Type <> 'A'
WHERE p2.BusinessId IS NULL

还有小提琴

祝你好运。

于 2013-01-30T14:01:57.933 回答
2

首先选择只有一种产品类型的企业,然后将其加入到您的原始表格中。

DECLARE @tbl TABLE
    (
     B_ID INT,
     prod_type VARCHAR(100)
    )

INSERT  INTO @tbl
        (B_ID, prod_type)
VALUES  (123, 'A'),
        (123, 'A'),
        (123, 'B'),
        (234, 'A'),
        (234, 'C'),
        (234, 'C'),
        (456, 'A'),
        (456, 'D'),
        (789, 'A') ;

WITH    businessIdsWithOneProductType
          AS (SELECT    B_ID
              FROM      @tbl t
              GROUP BY  B_ID
              HAVING    COUNT(DISTINCT prod_type) = 1)
    SELECT  *
    FROM    businessIdsWithOneProductType
            INNER JOIN @tbl ON businessIdsWithOneProductType.B_ID = [@tbl].B_ID
于 2013-01-30T14:09:04.910 回答
0
SELECT a.*
FROM    tableName a
        LEFT JOIN tableName b
            ON a.B_ID = b.B_ID AND
                b.prod_type IN ('B','C','D')
WHERE b.B_ID IS NULL
于 2013-01-30T14:04:13.010 回答