我想从列相同的表中检索数据

时间:2013-10-07 09:53:55

标签: sql rows

我有一个名为product的表,其中包含以下数据:

maker model type
A   1232    PC
A   1233    PC
A   1276    Printer
A   1298    Laptop
A   1401    Printer
A   1408    Printer
A   1752    Laptop
B   1121    PC
B   1750    Laptop
C   1321    Laptop
D   1288    Printer
D   1433    Printer
E   1260    PC
E   1434    Printer
E   2112    PC
E   2113    PC

我想检索制造商和类型

条件1:仅生产相同类型的型号 条件2:这些模型的数量超过1。

期望的结果:

maker   type
D       Printer

4 个答案:

答案 0 :(得分:3)

要获得制造商:

select distinct maker
from your_table
group by maker
having count(distinct type) = 1
and count(*) > 1

获取制造商并输入:

select distinct t.maker, t.type
from your_table t
inner join
(
   select maker
   from your_table
   group by maker
   having count(distinct type) = 1
   and count(*) > 1
) x on x.maker = t.maker

答案 1 :(得分:2)

请尝试:

select 
    distinct Maker, Type 
from(
    select 
        *, 
        COUNT(*) over (partition by Maker, type) TypeCnt,
        COUNT(*) over (partition by Maker) MakerCnt
    from YourTable
)x where TypeCnt=MakerCnt and TypeCnt>1

答案 2 :(得分:1)

SELECT types.[maker],  types.[type] FROM
(SELECT [maker],   COUNT([model]) as cnt
FROM Table1
GROUP BY [maker]) makers
INNER JOIN
(SELECT [maker],  [type], COUNT([model]) as cnt
FROM Table1
GROUP BY [maker],  [type]) types
ON makers.[maker] = types.[maker]
AND makers.cnt = types.cnt
AND types.cnt > 1

<强> SAMPLE FIDDLE

答案 3 :(得分:1)

SELECT maker, MIN(type) AS type
FROM product
GROUP BY maker
HAVING MIN(type) = MAX(type)
   AND COUNT(DISTINCT model) > 1 ;