0

我有一个运行良好的 SQL Server 查询——直到我将一个计算列添加到 SELECT 语句。然后我得到一个奇怪的 SQL Server 错误。

这是SQL:

SELECT
    outmail_.MessageID_, 
    CONVERT(VARCHAR(10),outmail_.Created_,120) AS 'Issue', 
    lyrReportSummaryData.mailed, 
    lyrReportSummaryData.successes, 
    COUNT(*) AS 'opens',
    COUNT(DISTINCT clicktracking_.MemberID_) AS 'unique_opens', 
    convert(decimal(3,1),((convert(float,[unique_opens]))/[successes]) * 100) AS 'Rate'
FROM 
    outmail_ 
RIGHT JOIN 
    clicktracking_ ON clicktracking_.MessageID_ = outmail_.MessageID_
RIGHT JOIN 
    lyrReportSummaryData ON lyrReportSummaryData.id = clicktracking_.MessageID_ 
GROUP BY  
    outmail_.MessageID_, CONVERT(VARCHAR(10), outmail_.Created_,120), 
    lyrReportSummaryData.mailed, lyrReportSummaryData.successes

问题是以包含时开头的行convert(decimal ... ,我收到以下错误:

错误 8120:列 'lyrReportSummaryData.unique_opens' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

我不确定如何解决该错误,因为我不知道如何在GROUP BY子句中使用它(而且我似乎不需要这样做)。

有关如何进行的任何建议?谢谢。

4

1 回答 1

2

我敢肯定,比我有更好的 DBA 技能的人可以指出一种更有效的方法,但是......

如果您将大部分查询作为子查询执行,则可以对子查询的结果进行计算:

 SELECT 
    MessageID_, 
    Issue, 
    mailed, 
    successes, 
    opens, 
    unique_opens, 
    convert(decimal(3,1),((convert(float,[unique_opens]))/[successes]) * 100) AS 'Rate'

 FROM 
 (SELECT
      outmail_.MessageID_, 
      CONVERT(VARCHAR(10),outmail_.Created_,120) AS 'Issue', 
      lyrReportSummaryData.mailed, 
      lyrReportSummaryData.successes, 
      COUNT(*) AS 'opens',
      COUNT(DISTINCT clicktracking_.MemberID_) AS 'unique_opens'


    FROM outmail_ 
    RIGHT JOIN clicktracking_ ON clicktracking_.MessageID_ = outmail_.MessageID_
    RIGHT JOIN lyrReportSummaryData ON lyrReportSummaryData.id = clicktracking_.MessageID_ 

    GROUP BY  outmail_.MessageID_, CONVERT(VARCHAR(10), outmail_.Created_,120), lyrReportSummaryData.mailed, lyrReportSummaryData.successes
   ) subquery /* was 'g' */

实际上,它所做的是运行分组,然后在此基础上进行计算。

必须给子查询一个别名(在本例中为“子查询”)——即使您不使用该别名。

于 2012-06-21T00:57:46.927 回答