[英]Distinct Count & Distinct Count with Condition in a Single Query
Model ID ![]() |
Work Order Number![]() |
Purchase Order Lines![]() |
---|---|---|
123 ![]() |
x ![]() |
5450 ![]() |
123 ![]() |
x ![]() |
5400 ![]() |
123 ![]() |
y![]() |
5200 ![]() |
123 ![]() |
y![]() |
5500 ![]() |
I have something like the table above in my SQL Server database.我的 SQL 服务器数据库中有类似上表的内容。 I want a query to return the the distinct Model ID, count of distinct Work Orders, and distinct count of work orders where Purchase Order Lines are not 5450 or 5400.
我想要一个查询来返回不同的 Model ID、不同的工作订单计数以及采购订单行不是 5450 或 5400 的不同工作订单计数。
From the table above the result of the query should be as follows:从上表中查询的结果应该如下:
Model ID ![]() |
Distinct Work Orders![]() |
Distinct Work Orders excluding PO lines 5400 and 5450![]() |
---|---|---|
123 ![]() |
2 ![]() |
1 ![]() |
Is there a way to do this without using multiple sub queries or temporary tables?有没有办法在不使用多个子查询或临时表的情况下做到这一点?
I suspect that you might actually mean work orders that do not have 5400 or 5450, even if they have other values.我怀疑您实际上可能指的是没有 5400 或 5450 的工单,即使它们有其他值。
You can do this with a difference:您可以通过以下方式做到这一点:
select count(distinct workorder),
(count(distinct workorder) -
count(distinct case when purchaseorder not in (5400, 5450) then workorder end)
)
from t;
You can use COUNT DISTINCT with a case statement.您可以将 COUNT DISTINCT 与 case 语句一起使用。 Something like this...
像这样的东西...
SELECT COUNT(DISTINCT ColumnName)
, COUNT(DISTINCT ( CASE WHEN SomeCondition = True THEN ColumnName ELSE NULL END)) FilteredDistCount
FROM TableName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.