2

我在这里尝试了最佳答案:选择计数/重复 并没有得到准确的结果,可能是因为这个例子是针对一个字段的?

我最初尝试过这个,但似乎也没有工作:

   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

建议?

4

3 回答 3

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
于 2012-12-07T06:53:42.587 回答
0

据我了解,您希望获取计数 > 1 的所有记录。

select T.State, T.City, COUNT(1)
FROM TABLE T
GROUP BY T.State, T.City
HAVING COUNT(1) > 1
于 2012-12-07T06:16:21.040 回答
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
于 2012-12-07T06:16:44.027 回答