3

我有一张这样的桌子:

Item    ProviderId

Item1   1

Item1   2

Item2   1

Item3   1

我希望得到一张新桌子。在新表中,它只列出了item至少有两个不同ProviderIds 的 s。

所以在上面的例子中,因为只有item1两个不同的ProviderId我希望得到这样的表:

Item

Item1

我怎样才能写出声明来做到这一点?

4

3 回答 3

3

你必须使用group byhaving

select item
from table
group by item
having count(distinct ProviderId)>=2

或没有distinct

select item
from tab
group by item, ProviderId
having count(1)>=2;

sql 小提琴演示

以查询为表:

select item
from (select item, ptoviderId from tabA) as tab
group by item, ProviderId
having count(1)>=2;

如果要创建新表,可以使用into

select item
into newTable
from table
-- or (select item, ptoviderId from tabA)
group by item
having count(distinct ProviderId)>=2
于 2012-10-24T10:09:44.850 回答
2

试试这个:

 SELECT [Item]      
      FROM [TABLE_NAME]
      GROUP BY [Item]
      HAVING COUNT(DISTINCT ProviderId) >1
    GO
于 2012-10-24T10:25:31.320 回答
1
INSERT INTO <your new table> (newTableItem)
    (SELECT Item
    FROM <table>
    GROUP BY Item
    HAVING COUNT(DISTINCT ProviderId) > 1)-- or just HAVING COUNT(*) > 1 if one Item can't have two times the same ProviderId
于 2012-10-24T10:09:56.810 回答