我有一个名为ItemTransaction
的表,列itemId, Qty, BatchNo
列。我想选择所有具有qty >=0
和<= 100
以及itemid
和batchno
唯一的项目。
现在的问题是,可以在具有不同batchno
的不同qty
中重复单个项目。
select
ItemID, Quantity, BatchNo
from
ItemTransaction
where
Quantity >= 0 and Quantity <= 100
group by
ItemID, Quantity, BatchNo
当我运行上述查询时,它会给出重复值。不知道如何从上述条件中获取不同的值。
示例数据
|ItemID | Quantity | BatchNo |
+----------------------------+
|1095 | 3 | 1 |
|1095 | 0 | 1 |
|1098 | 10 | 2 |
|1099 | 0 | 3 |
|1099 | 20 | 3 |
|1099 | 80 | 3 |
预期产出:
|ItemID | Quantity | BatchNo |
+----------------------------+
|1095 | 3 | 1 |
|1098 | 10 | 2 |
|1099 | 80 | 3 |
此处数量可以是批次中较大或批次较小的任何数量。
答案 0 :(得分:2)
试试这个。
SELECT ItemID,
Max(Quantity)Quantity,
BatchNo
FROM ItemTransaction
WHERE Quantity >= 0
AND Quantity <= 100
GROUP BY ItemID,
BatchNo
答案 1 :(得分:0)
添加Distinct
关键字
select Distinct ItemID, Quantity, BatchNo
from ItemTransaction
where Quantity >= 0 and Quantity <= 100
group by ItemID,Quantity,BatchNo
答案 2 :(得分:0)
在分组后添加having子句并且distinct也是正确的
select ItemID,Quantity,BatchNo from ItemTransaction
where Quantity >= 0 and Quantity <= 100
group by ItemID,Quantity,BatchNo
having count(ItemID)=1 ;
当我发布上述答案时,您的问题尚未完成;截至目前它具有预期的输出,因此下面的查询将给出正确的答案。
select ItemID,Quantity,BatchNo from Itm
where Quantity >= 0 and Quantity <= 100 and
(ItemID,Quantity) in
(select ItemID,max(Quantity) from itm group by ItemID) ;