SQL查询以查看查询是否同时包含两种类型

时间:2019-07-02 19:28:36

标签: sql sql-server

我正在尝试创建另一列,如果在两个工厂中都有项目号,则为Y;如果仅在1个工厂中,则为N。

Raw data:
ItemNum   Item    Plant
1         apple   rightplant
2         orange  leftplant
2         grape   rightplant
1         apple   left plant

Expected outcome:
ItemNum   Item    Plant       PlantBoth
1         apple   rightplant      Y
2         orange  leftplant       N
2         grape   rightplant      N
1         apple   left plant     Y

尝试(我可能需要一个案例来证明我假设的Y或N是正确的):

Select mi.ItemNum, mi.Item, mi.Plant, 
(Select plant from myitems where itemnum = mi.itemnum and count(plant) > 1) as Plantboth 
from  myitems mi

3 个答案:

答案 0 :(得分:1)

您可以使用窗口功能:

select i.*,
       (case when min(plant) over (partition by itemnum, item) <>
                  max(plant) over (partition by itemnum, item)
             then 'Y'
             else 'N'
        end) as PlantBoth
from myitems i;

答案 1 :(得分:0)

您可以尝试这种方式

--Create test data
declare @data table( itemNum int, Item varchar(20), Plant varchar(20))

insert into @data (itemNum, Item, Plant)
select 1, 'apple','rightplant' union
select 2, 'orange','rightplant' union
select 2, 'grape','leftplant' union
select 1, 'apple','leftplant'

--A left join returns all data from D1 and optionally D2 if there is a match.
--The case statement looks to see if there is a match.

select d1.*, 
case when d2.itemNum is null then 'N' else 'Y' end as [Match]
from @data D1
left join @data D2 
    on d1.itemNum = d2.itemNum and d1.Item = D2.item and d1.plant != d2.plant

答案 2 :(得分:0)

按itemnum,item分组以获取植物数量并加入表格:

select 
  m.*,
  case g.counter when 2 then 'Y' else 'N' end plantboth 
from myitems m inner join (
  select itemnum, item, count(distinct plant) counter
  from myitems 
  group by itemnum, item
) g on g.itemnum = m.itemnum and g.item = m.item