sql - 如何计算两行的差异?

时间:2012-10-24 10:08:02

标签: sql sql-server

我有一张这样的表:

Item    ProviderId

Item1   1

Item1   2

Item2   1

Item3   1

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

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

Item

Item1

如何编写声明来执行此操作?

3 个答案:

答案 0 :(得分: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 fiddle演示

将查询作为表格:

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

答案 1 :(得分:2)

试试这个:

 SELECT [Item]      
      FROM [TABLE_NAME]
      GROUP BY [Item]
      HAVING COUNT(DISTINCT ProviderId) >1
    GO

答案 2 :(得分: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