使用GROUP BY
和HAVING
从句COUNT(*) > 1
。
这是一个工作示例:http ://sqlfiddle.com/#!3/d1b91/17
在下面粘贴代码和结果:
CREATE TABLES(注意:没有放置 FK Constaint 用于演示目的)
CREATE TABLE Customer
(
customernbr NVARCHAR(20) NOT NULL
)
CREATE TABLE Meter
(
meternbr NVARCHAR(20) NOT NULL,
customernbr NVARCHAR(20) NOT NULL
)
插入数据。(如果您想查看数据,请取消注释最后 2 个 SELECT 语句)
INSERT INTO Customer VALUES
('a'),
('b'),
('c'),
('d');
INSERT INTO Meter VALUES
('a-100','a'),
('a-101','a'),
('b-103','b'),
('c-104','c'),
('c-105','c'),
('d-106','d');
--SELECT * FROM Customer;
--SELECT * FROM Meter;
运行选择语句
SELECT
customernbr AS 'Customer',
meternbr AS 'Meter'
FROM Meter WHERE customernbr IN
(
SELECT customernbr
FROM Meter
GROUP BY customernbr
HAVING COUNT(*) > 1
)
查看结果:)
CUSTOMER METER
a a-100
a a-101
c c-104
c c-105