我的一个SQL Server 2008查询中出现了令人沮丧的错误。它解析得很好,但在我尝试执行时崩溃了。我得到的错误如下:
Msg 8120,Level 16,State 1,Line 4
柱 'customertraffic_return.company'是 因为它在选择列表中无效 不包含在任何一个 聚合函数或GROUP BY 子句。
SELECT *
FROM (SELECT ctr.sp_id AS spid,
Substring(ctr.company, 1, 20) AS company,
cci.email_address AS tech_email,
CASE
WHEN rating IS NULL THEN 'unknown'
ELSE rating
END AS rating
FROM customer_contactinfo cci
INNER JOIN customertraffic_return ctr
ON ctr.sp_id = cci.sp_id
WHERE cci.email_address <> ''
AND cci.email_address NOT LIKE '%hotmail%'
AND cci.email_address IS NOT NULL
AND ( region LIKE 'Europe%'
OR region LIKE 'Asia%' )
AND SERVICE IN ( '1', '2' )
AND ( rating IN ( 'Premiere', 'Standard', 'unknown' )
OR rating IS NULL )
AND msgcount >= 5000
GROUP BY ctr.sp_id,
cci.email_address) AS a
WHERE spid NOT IN (SELECT spid
FROM customer_exclude)
GROUP BY spid,
tech_email
答案 0 :(得分:4)
嗯,错误非常清楚,没有?
您在内部SELECT中选择了这些列:
和您的分组只有其中两个(GROUP BY ctr.sp_id, cci.email_address
)。
要么所有四个都需要分组(GROUP BY ctr.sp_id, cci.email_address, company, rating
),要么需要将聚合函数(SUM,AVG,MIN,MAX)应用于其他两列(company
和{ {1}})。
或许在这里使用GROUP BY完全是错误的做法 - 你真的想在这做什么?
答案 1 :(得分:2)
内部查询:
SELECT ctr.sp_id AS spid,
Substring(ctr.company, 1, 20) AS company,
cci.email_address AS tech_email,
CASE
WHEN rating IS NULL THEN 'unknown'
ELSE rating
END AS rating
FROM customer_contactinfo cci
INNER JOIN customertraffic_return ctr
ON ctr.sp_id = cci.sp_id
WHERE cci.email_address <> ''
AND cci.email_address NOT LIKE '%hotmail%'
AND cci.email_address IS NOT NULL
AND ( region LIKE 'Europe%'
OR region LIKE 'Asia%' )
AND SERVICE IN ( '1', '2' )
AND ( rating IN ( 'Premiere', 'Standard', 'unknown' )
OR rating IS NULL )
AND msgcount >= 5000
GROUP BY ctr.sp_id,
cci.email_address
在选择中有4个非聚合内容(sp_id
,company
,email_address
,rating
)并且您只对其中两个进行分组,因此它会抛出它看到的第一个错误
所以你要么不需要按任何一个分组,要么全部分组
答案 2 :(得分:1)
我建议用完全指定的列列表替换*。
答案 3 :(得分:1)
您可以按所有选定的列进行分组,也可以在聚合函数中使用其他列(不在group by子句中)(如sum)
你不能:select a,b,c from bla group by a,b
但你可以:select a,b,sum(c) from bla groupy by a,b