'Typeorm How Can I get Min field with Where clause?
I use Typeorm and nestjs in my project. I have Schema:
export class GroupEntity implements IGroup {
// Attributes
@PrimaryGeneratedColumn({ type: 'string' })
public id: string;
@Column({ type: 'string', nullable: false })
public userId: string;
@Column({ type: 'int2' })
public syncStatus: number;
}
I want to get min sync status by userId where syncStatus is not null
exampleData:
[{
id: "1",
userId: "101",
syncStatus: 2
}, {
id: "2",
userId: "101",
syncStatus: 3
}, {
id: "2",
userId: "105",
syncStatus: -5
}, {
id: "2",
userId: "101",
syncStatus: null
}]
expected result
2
or row with value 2
Big thx!
Solution 1:[1]
You simply need to use MIN
, Here's how:
return this.groupRepository.createQueryBuilder('group')
.select("MIN(group.syncStatus)",'syncStatus')
.addSelect(['group.id','group.userId'])
.where('group.userId = :user", {
user,
})
.andWhere('group.syncStatus is not null')
.getRawOne();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Youba |