如何根据合并列的值过滤分组查询?
这是我的查询不起作用,因为它显然违反了 HAVING 子句的规则:
SELECT
COALESCE(Publisher.name, Affiliate.name) AS Publisher
,dbo.SumKeys(Item.id) AS ItemIDs
FROM
Item
INNER JOIN ItemAccountingStatus ON Item.item_accounting_status_id = ItemAccountingStatus.id
INNER JOIN Affiliate ON Item.affid = Affiliate.affid
INNER JOIN Currency AffiliateCurrency ON Affiliate.currency_id = AffiliateCurrency.id
INNER JOIN Campaign ON Item.pid = Campaign.pid
INNER JOIN CampaignStatus ON Campaign.campaign_status_id = CampaignStatus.id
LEFT OUTER JOIN Publisher ON Affiliate.affid = Publisher.affid
GROUP BY
COALESCE(Publisher.name, Affiliate.name)
,ItemAccountingStatus.name
,CampaignStatus.name
HAVING (
ItemAccountingStatus.name='default'
and CampaignStatus.name='Verified'
and Publisher='AdsMain LLC' -- THIS BREAKS THE QUERY
)
问题:有什么方法可以做到这一点吗?
Here's my Query that does not work because it apparently violates the rules of the HAVING clause:
SELECT
COALESCE(Publisher.name, Affiliate.name) AS Publisher
,dbo.SumKeys(Item.id) AS ItemIDs
FROM
Item
INNER JOIN ItemAccountingStatus ON Item.item_accounting_status_id = ItemAccountingStatus.id
INNER JOIN Affiliate ON Item.affid = Affiliate.affid
INNER JOIN Currency AffiliateCurrency ON Affiliate.currency_id = AffiliateCurrency.id
INNER JOIN Campaign ON Item.pid = Campaign.pid
INNER JOIN CampaignStatus ON Campaign.campaign_status_id = CampaignStatus.id
LEFT OUTER JOIN Publisher ON Affiliate.affid = Publisher.affid
GROUP BY
COALESCE(Publisher.name, Affiliate.name)
,ItemAccountingStatus.name
,CampaignStatus.name
HAVING (
ItemAccountingStatus.name='default'
and CampaignStatus.name='Verified'
and Publisher='AdsMain LLC' -- THIS BREAKS THE QUERY
)
QUESTION: is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑您是否需要having子句 - 在where子句中尝试如下
I doubt if you need a having clause - try it in the where clause as below
仅在 ORDER BY 中允许使用列别名。您必须在 WHERE、GROUP BY、HAVING 等中使用表达式(生成别名列)。您已经按照预期在 GROUP BY 中使用了表达式。
有些 DBMS 允许您在其他地方引用列别名,但 SQL Server 不允许,我认为这使得发生的情况更加明显。
或者您可以使用派生表/CTE 方法并从中选择(根据您的自我回答)
按照 MSDN 上的 SELECT,“SELECT 语句的逻辑处理顺序”
Column aliases are allowed only in the ORDER BY. You must use the expression (that generates the aliased column) in WHERE, GROUP BY, HAVING etc. You've already used the expression in the GROUP BY though as expected.
Some DBMS allow you to reference column aliases in other places but not SQL Server, which I think makes it more obvious what is going on.
Or you can use a derived table/CTE approach and SELECT from that (as per your self-answer)
As per SELECT on MSDN, "Logical Processing Order of the SELECT statement"