我有一个运行得很好的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
子句中使用它(而且似乎我不应该这样做)。
有关如何进行的任何建议?感谢。
答案 0 :(得分: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' */
这实际上是运行分组,然后基于此,然后进行计算。
必须为子查询指定别名(在本例中为“子查询”) - 即使您不使用该别名。