SQL根据其他行

时间:2017-02-27 17:26:50

标签: sql

如果购买SKU A,我正试图查看已购买的其他SKU。

到目前为止我所拥有的是:

Select *
    From Test 
    Where Transaction ID = Sku 'A'

但当然where语句不起作用。我没有能力创建新表或任何东西,但我认为应该可以只进行查询?任何帮助将不胜感激,因为我在这里拔头发!

谢谢!

表名:测试(Original Image):

+ -------------- + --- + ----------------- +
| Transaction ID | SKU | Desired in Output |
+ -------------- + --- + ----------------- +
| 1              | A   | Y                 |
| 1              | B   | Y                 |
| 2              | A   | Y                 |
| 2              | D   | Y                 |
| 3              | F   | N                 |
| 3              | G   | N                 |
+ -------------- + --- + ----------------- +

3 个答案:

答案 0 :(得分:1)

您可以使用子查询

Select *
    From Test 
    Where Transaction_ID in (
        select Transaction_ID
            from Test
            where SKU = 'A'
    )

答案 1 :(得分:0)

您可以在exists()中使用where,如下所示:

select *
from t
where exists (
  select 1
  from t as i
  where i.TransactionId = t.TransactionId
    and Sku = 'A'
);

答案 2 :(得分:0)

使用内部联接选择包含A:

的交易ID
create table #test
(
Transaction_id int,
Sku varchar(1)
)

insert into #test (Transaction_id, Sku) values (1, 'A')
insert into #test (Transaction_id, Sku) values (1, 'B')
insert into #test (Transaction_id, Sku) values (2, 'A')
insert into #test (Transaction_id, Sku) values (2, 'D')
insert into #test (Transaction_id, Sku) values (3, 'F')
insert into #test (Transaction_id, Sku) values (3, 'G')

select t.Transaction_id, t.Sku
from #test t
join 
(
    select Transaction_id
    from #test
    where Sku = 'A'

) x on x.Transaction_id = t.Transaction_id

drop table #test