简体   繁体   English

当DISTINCT为默认值时,SELECT查询返回值

[英]SELECT query to return value when DISTINCT else default value

I feel this should be a simple SELECT query but cannot get it to work. 我觉得这应该是一个简单的SELECT查询,但无法让它工作。

Essentially, in this example, I want to return a distinct list of Order_IDs, along with the Country: 基本上,在这个例子中,我想返回一个不同的Order_ID列表,以及Country:

  • if there is one country associated with the Order_ID, return that Country value 如果有一个国家/地区与Order_ID相关联,则返回该国家/地区值

  • if there are multiple countries associated, return a default value ('Multiple'). 如果有多个国家/地区关联,则返回默认值(“多个”)。

- -

SELECT [Order_ID]
    ,CASE WHEN COUNT(DISTINCT [Country]) = 1 THEN [Country] ELSE 'Multiple' END as [Combined_Country]
    FROM [Sales Data]
    GROUP BY [Order_ID]

At the moment this returns the error "Column 'Sales Data.Country' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." 此时返回错误“列'Sales Data.Country'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”

Adding Country to the GROUP BY clause however results in multiple rows being returned for each country associated with the order, rather than one row with the default value 'Multiple'. 然而,将Country添加到GROUP BY子句会导致为与订单关联的每个国家/地区返回多行,而不是一行具有默认值“Multiple”。

Any help? 有帮助吗?

You need to aggregate what you aren't grouping. 您需要汇总您不分组的内容。 I believe this should work for you: 我相信这对你有用:

SELECT 
    [Order_ID]
    , CASE WHEN COUNT(Country) > 1 THEN 'Multiple' ELSE MAX(Country) END AS [Combined_Country]
FROM [Sales Data]
GROUP BY 
    [Order_ID]  

Here, when looking at country, we are always aggregating. 在这里,当看到国家时,我们总是在聚合。 The COUNT() aggregation is what you really care about, but we need to use another aggregate function, in my case MAX(), even when trying to read the single value. COUNT()聚合是你真正关心的,但我们需要使用另一个聚合函数,在我的情况下MAX(),即使在尝试读取单个值时也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM