在尝试 GROUP BY VARCHAR 字段时,我目睹了一种奇怪的行为。
以下示例,我尝试发现过去至少更改过一次名字的客户。
CREATE TABLE #CustomersHistory
(
Id INT IDENTITY(1,1),
CustomerId INT,
Name VARCHAR(200)
)
INSERT INTO #CustomersHistory VALUES (12, 'AAA')
INSERT INTO #CustomersHistory VALUES (12, 'AAA')
INSERT INTO #CustomersHistory VALUES (12, 'BBB')
INSERT INTO #CustomersHistory VALUES (44, '444')
SELECT ch.CustomerId, count(ch.Name) AS cnt
FROM #CustomersHistory ch
GROUP BY ch.CustomerId HAVING count(ch.Name) != 1
奇怪的产生(好像第一次INSERT的'AAA'与第二次INSERT不同)
CustomerId cnt // (I was expecting)
12 3 // 2
44 1 // 1
注意:此问题与GROUP BY problem with varchar非常相似,我找不到为什么的答案
旁注:使用HAVING count(ch.Name) != 1
代替HAVING count(ch.Name) > 1
是不错的做法?
答案 0 :(得分:2)
COUNT()
运算符将计算所有行,而不考虑值。我想你可能想要使用只计算唯一名称的COUNT(DISTINCT ch.Name)
。
SELECT ch.CustomerId, count(DISTINCT ch.Name) AS cnt
FROM #CustomersHistory ch
GROUP BY ch.CustomerId HAVING count(DISTINCT ch.Name) > 1
有关详细信息,请查看在线图书上的COUNT()文章