单个查询中的非重复计数和带条件的非重复计数
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
我的 SQL 服务器数据库中有类似上述 table 的内容。我想查询 return 不同的模型 ID、不同的工作订单计数和采购订单行不是 5450 或 5400 的工作订单的不同计数。
从上面的table查询出来的结果应该是这样的:
Model ID
Distinct Work Orders
Distinct Work Orders excluding PO lines 5400 and 5450
123
2
1
有没有办法在不使用多个子查询或临时 tables 的情况下做到这一点?
您可以将 COUNT DISTINCT 与 case 语句一起使用。像这样...
SELECT COUNT(DISTINCT ColumnName)
, COUNT(DISTINCT ( CASE WHEN SomeCondition = True THEN ColumnName ELSE NULL END)) FilteredDistCount
FROM TableName
我怀疑您实际上可能指的是没有 5400 或 5450 的工单,即使它们有其他值。
你可以做一些不同的事情:
select count(distinct workorder),
(count(distinct workorder) -
count(distinct case when purchaseorder not in (5400, 5450) then workorder end)
)
from t;
Model ID | Work Order Number | Purchase Order Lines |
---|---|---|
123 | x | 5450 |
123 | x | 5400 |
123 | y | 5200 |
123 | y | 5500 |
我的 SQL 服务器数据库中有类似上述 table 的内容。我想查询 return 不同的模型 ID、不同的工作订单计数和采购订单行不是 5450 或 5400 的工作订单的不同计数。
从上面的table查询出来的结果应该是这样的:
Model ID | Distinct Work Orders | Distinct Work Orders excluding PO lines 5400 and 5450 |
---|---|---|
123 | 2 | 1 |
有没有办法在不使用多个子查询或临时 tables 的情况下做到这一点?
您可以将 COUNT DISTINCT 与 case 语句一起使用。像这样...
SELECT COUNT(DISTINCT ColumnName)
, COUNT(DISTINCT ( CASE WHEN SomeCondition = True THEN ColumnName ELSE NULL END)) FilteredDistCount
FROM TableName
我怀疑您实际上可能指的是没有 5400 或 5450 的工单,即使它们有其他值。
你可以做一些不同的事情:
select count(distinct workorder),
(count(distinct workorder) -
count(distinct case when purchaseorder not in (5400, 5450) then workorder end)
)
from t;