1

我正在尝试编写一个查询以从我们的数据库中提取一些信息,并且我需要按字符串的一部分对其进行分组。所以我做了 GROUP BY substring()。但是,即使我 substring()ing 的列在 SELECT 语句中,它似乎仍然失败。我还尝试将 substr() 放在它自己的选择中并用它做一个“AS x”,但这也失败了,因为它是在 GROUP BY 之后执行的。

SELECT 
M.Cabot_source, 
CASE substring(M.Cabot_source,6,1) 
WHEN 'C' THEN 'CoregUserNameLC' 
WHEN 'P' THEN 'PPC' 
WHEN 'O' THEN 'Organic' 
WHEN 'S' THEN 'Ad Swap' 
WHEN 'I' THEN 'Internal' 
ELSE 'Unknown' 
END as source_type
FROM members_ M 
WHERE M.Cabot_source != '' 
GROUP BY substring(M.Cabot_source,6,1)

这是它返回给我的错误:

从 db Connection 报告的 SQL 错误:

> (0x3ddbe8) Lyris function: SQLClass::SendToSQLInternal()  Lyris error
> description: Command.Open() failed with error code 80040e14  Database
> error information: Error 8120: Column 'members_.Cabot_source' is
> invalid in the select list because it is not contained in either an
> aggregate function or the GROUP BY clause.  (source: Microsoft OLE DB
> Provider for SQL Server)  SQL Statement: SELECT M.Cabot_source, CASE
> substring(M.Cabot_source,6,1) WHEN 'C' THEN 'CoregUserNameLC' WHEN 'P'
> THEN 'PPC' WHEN 'O' THEN 'Organic' WHEN 'S' THEN 'Ad Swap' WHEN 'I'
> THEN 'Internal' ELSE 'Unknown' END as source_type FROM members_ M
> WHERE M.Cabot_source != '' GROUP BY substring(M.Cabot_source,6,1)
4

3 回答 3

2

您必须对完整的案例陈述进行分组。

SELECT 
M.Cabot_source, 
  CASE substring(M.Cabot_source,6,1) 
   WHEN 'C' THEN 'CoregUserNameLC' 
   WHEN 'P' THEN 'PPC' 
   WHEN 'O' THEN 'Organic' 
   WHEN 'S' THEN 'Ad Swap' 
   WHEN 'I' THEN 'Internal' 
   ELSE 'Unknown' 
  END as source_type
FROM members_ M 
WHERE M.Cabot_source != '' 
GROUP BY 
  M.Cabot_source, 
  CASE substring(M.Cabot_source,6,1) 
   WHEN 'C' THEN 'CoregUserNameLC' 
   WHEN 'P' THEN 'PPC' 
   WHEN 'O' THEN 'Organic' 
   WHEN 'S' THEN 'Ad Swap' 
   WHEN 'I' THEN 'Internal' 
   ELSE 'Unknown' 
  END
于 2012-06-28T18:07:26.603 回答
0

错误的罪魁祸首是:

(SELECT COUNT(*) FROM members_ M3 WHERE M3.Cabot_source = M.Cabot_source) as names, 
(SELECT COUNT(*) FROM members_ M2 WHERE M2.MemberType_ = 'normal' AND M2.Cabot_source = M.Cabot_source) 
于 2012-06-28T15:45:15.973 回答
0

你可以:

select M.Cabot_source + group by M.Cabot_source

或使用任何聚合函数,例如:

 select max(M.Cabot_source)

唯一的例外是 MySQL,它有一个隐式聚合函数 - 我称之为它return_random_record(M.Cabot_source),但 MySQL 的这种默认(可能未定义)行为在 SQL Server 驱动程序中不可用

于 2012-06-28T16:40:19.427 回答