我在这里尝试了最好的答案:Select count / duplicates 并没有得到准确的结果,也许是因为这个例子适用于一个领域?
我原本试过这个,但似乎也没有用:
SELECT T.STATE, T.CITY, COUNT(T2.CITY)
FROM (SELECT DISTINCT T.STATE, T.CITY
FROM TABLE ) T
LEFT JOIN TABLE T2 ON T2.STATE = T.STATE
AND T2.CITY = T.CITY
GROUP BY T.STATE, T.CITY
这也会产生不准确的结果。我正在尝试获取表中2个字段的重复值的计数。
示例数据:
Los Angeles, CA, Bob
New York, NY, Bill
Los Angeles, CA, Jim
Los Angeles, CA, Joe
New York, NY, Gary
Los Angeles, CA, Roger
应该回归:
Los Angeles, CA, 4
New York, NY, 2
建议?
答案 0 :(得分:1)
DECLARE @TABLE TABLE(
CITY VARCHAR(100),
[STATE] CHAR(2),
NAME VARCHAR(50)
)
INSERT INTO @TABLE VALUES
('Los Angeles', 'CA', 'Bob'),
('New York', 'NY', 'Bill'),
('Los Angeles', 'CA', 'Jim'),
('Los Angeles', 'CA', 'Joe'),
('New York', 'NY', 'Gary'),
('Los Angeles', 'CA', 'Roger')
SELECT CITY,[STATE],COUNT(*) [COUNT]
FROM @TABLE
GROUP BY CITY,[STATE]
HAVING COUNT(*) > 1
--if there are erroneous white spaces and inconsistant case, and collation is case sensitive use this
DELETE FROM @TABLE
INSERT INTO @TABLE VALUES
(' Los Angeles', 'CA', 'Bob'),
('New York', 'NY', 'Bill'),
('Los ANgeles ', 'CA', 'Jim'),
('LOS Angeles', 'CA', 'Joe'),
('New YorK ', 'NY', 'Gary'),
(' Los Angeles ', 'CA', 'Roger')
SELECT RTRIM(LTRIM(UPPER(CITY))) [CITY] ,RTRIM(LTRIM(UPPER([STATE]))) [STATE],COUNT(*) [COUNT]
FROM @TABLE
GROUP BY RTRIM(LTRIM(UPPER(CITY))),RTRIM(LTRIM(UPPER([STATE])))
HAVING COUNT(*) > 1
答案 1 :(得分:0)
根据我的理解,您希望获得所有具有计数的记录> 1。
select T.State, T.City, COUNT(1)
FROM TABLE T
GROUP BY T.State, T.City
HAVING COUNT(1) > 1
答案 2 :(得分:0)
SELECT T.STATE, T.CITY, COUNT(*) as cnt
FROM Table X T
GROUP BY T.STATE, T.CITY
HAVING COUNT(*)>1
如果输入不准确,您可以尝试
SELECT RTRIM(LTRIM(T.STATE)), LTRIM(RTRIM(T.CITY)), COUNT(*) as cnt
FROM Table X T
GROUP BY RTRIM(LTRIM(T.STATE)), LTRIM(RTRIM(T.CITY))
HAVING COUNT(*)>1