[英]Microsoft Access sql query to find records where all values in a column match
I have a similar to below:我有一个类似于下面的:
ProductID![]() |
Division![]() |
OrdNum![]() |
---|---|---|
1 ![]() |
011 ![]() |
123 ![]() |
1 ![]() |
705 ![]() |
123 ![]() |
1 ![]() |
660 ![]() |
123 ![]() |
2 ![]() |
011 ![]() |
511 ![]() |
2 ![]() |
705 ![]() |
412 ![]() |
2 ![]() |
660 ![]() |
216 ![]() |
I am trying to write a query that will return each product ID and if the OrdNum for all Divisions is the same it will return the OrdNum, and if the OrdNums are different it will return "Varies"我正在尝试编写一个返回每个产品 ID 的查询,如果所有部门的 OrdNum 相同,它将返回 OrdNum,如果 OrdNum 不同,它将返回“Varies”
The results should look like this:结果应如下所示:
ProductID![]() |
OrdNum![]() |
---|---|
1 ![]() |
123 ![]() |
2 ![]() |
Varies![]() |
Consider:考虑:
Query1:查询1:
SELECT DISTINCT Table1.ProductID, Table1.OrdNum FROM Table1;
Query2:查询2:
SELECT ProductID, Count(OrdNum) AS CountOfOrdNum
FROM Query1
GROUP BY ProductID;
Query3:查询3:
SELECT Table1.ProductID, IIf([CountOfOrdNum]=1,[OrdNum],"Varies") AS Ord
FROM Query2 INNER JOIN Table1 ON Query2.ProductID = Table1.ProductID
GROUP BY Table1.ProductID, IIf([CountOfOrdNum]=1,[OrdNum],"Varies");
Below query may work for you.以下查询可能对您有用。
select t2.ProductID,iif(t2.OrdCount>1,"Varies",DLookup("[OrdNum]","[Table1]","[ProductID]="&t2.ProductID)) as OrdNum
from (select t1.ProductID, count(t1.ProductID) as OrdCount
from (select ProductID, OrdNum, Count(Division) AS CountOfDivision from Table1 group by ProductID, OrdNum) as t1 group by t1.ProductID) as t2
Just compare the min and max values:只需比较最小值和最大值:
Select
ProductID,
IIf(Min(OrdNum) = Max(OrdNum), First(OrdNum), "Varies") As OrderNumber
From
YourTable
Group By
ProductID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.