尝试使用SQL Server 2012在一个select语句中查看是否可能。
表是这个:
订单:
Order_Index Audit_ID
--------------------
101 CB
102 MM
103 CN
Audit_ID
CB和CN是同一个人,MM应该从结果中排除,所以我尝试显示以下内容:
SELECT
CASE
WHEN Audit_Id IN ('CB’, ’CN’)
THEN 'Cindy’
ELSE Audit_Id
END AS Audit_Id,
COUNT(DISTINCT Order_Index) AS ‘Total Orders’
FROM
Orders
WHERE
Audit_Id IN ('CB', 'CN’)
GROUP BY
Audit_Id
结果:
Audit_Id Total Orders
-------------------------
Cindy 1
Cindy 1
所需结果:
Audit_Id Total Orders
-------------------------
Cindy 2
单个查询是否有可能得到结果?
谢谢
布莱恩
答案 0 :(得分:0)
由于您的所有结果显然都在同一个组中,因此这里实际上不需要整个group by
子句:
select 'Cindy' as "Audit ID", count(*) as "Total Orders"
from Orders
where Audit_Id in ('CB','CN');
现在,如果您真正要完成的工作是某种“自定义”分组,那么您可能正在拍摄更多类似这样的内容:
select
case when Audit_ID in ('A', 'B') then 'Group1' ... else Audit_ID end as "Audit ID",
count(*) as "Total Orders"
from Orders
group by case when Audit_ID in ('A', 'B') then 'Group1' ... else Audit_ID end;
除非您仅将表达式嵌套在另一个引用(如派生表或CTE)中,否则您必须在group by
和select
列表之间复制表达式。