0
我有一張表,我想要捕獲重複值。如何從查詢中分離結果?
捕捉它們之後,我想將這些結果分隔成單獨的行。
表:
CREATE TABLE [dbo].[ContactTable](
[contactid] [int] IDENTITY(1,1) NOT NULL,
[telephone1] [varchar](100) NULL,
[telephone2] [varchar](100) NULL,
[fullname] [varchar](100) NOT NULL
) ON [PRIMARY]
幾個值:
insert into ContactTable(telephone1, telephone2,fullname) values('123','1234','danny')
insert into ContactTable(telephone1, telephone2,fullname) values('123','1234','danny1')
insert into ContactTable(telephone1, telephone2,fullname) values('123*','1234#','martin')
insert into ContactTable(telephone1, telephone2,fullname) values('1243*','15234#','martin')
insert into ContactTable(telephone1, telephone2,fullname) values('1243','15234','martin1')
捕捉重複值的查詢:
SELECT Phones, COUNT(Phones) AS CountPhones
FROM
(
SELECT Phones, contactid
FROM
(
SELECT telephone1 AS Phones, contactid
FROM ContactTable
WHERE (telephone1 IS NOT NULL)
UNION ALL
SELECT REPLACE(telephone1, '*', '') AS Phones, contactid
FROM ContactTable
WHERE (telephone1 IS NOT NULL) AND (telephone1 LIKE '%*')
UNION ALL
SELECT REPLACE(telephone1, '#', '') AS Phones, contactid
FROM ContactTable
WHERE (telephone1 IS NOT NULL) AND (telephone1 LIKE '%#')
UNION ALL
SELECT telephone2 AS Phones, contactid
FROM ContactTable
WHERE (telephone2 IS NOT NULL)
UNION ALL
SELECT REPLACE(telephone2, '*', '') AS Phones, contactid
FROM ContactTable
WHERE (telephone2 IS NOT NULL) AND (telephone2 LIKE '%*')
UNION ALL
SELECT REPLACE(telephone2, '#', '') AS Phones, contactid
FROM ContactTable
WHERE (telephone2 IS NOT NULL) AND (telephone2 LIKE '%#')
)as Tel
GROUP BY Phones, contactid
) as T
GROUP BY Phones
HAVING (COUNT(*) > 1)
ORDER BY CountPhones DESC
結果:
telephone Count
--------- -----
123 3
1234 3
1243 2
15234 2
但我想要得到的結果是這樣的:
id telephone fullname
-- --------- --------
1 123 danny
2 123 danny1
3 123 martin
3 1234 martin
1 1234 danny
2 1234 danny1
5 1243 martin1
4 1243 martin
4 15234 martin
5 15234 martin1
我怎樣才能做到這一點?
什麼定義了重複的請求? – gbn
的值 - 例如,如果手機號碼123,或123#或123 *,所以我有3個副本。 –