如何使用“ Min()”创建SQL Pypika查询

时间:2019-10-14 11:45:52

标签: python sql

我正在尝试创建一个使用SQL的MIN('')函数的Pypika查询。 Pypika supports the function,但我不知道如何使用。

基本上我想在Pypika中创建此SQL语句:

select 
"ID","Car","Road","House"
  from "thingsTable"
 where "ID" not in
 (
 select MIN("ID")
 from "thingsTable"
 GROUP BY 
"Car","Road","House"
)
order by "ID"

我尝试过这样的事情:

from pypika import Query, Table, Field, Function

query = Query.from_(table).select(min(table.ID)).groupby(table.Car, table.Road, table.House)

及其变体,但无法弄清楚如何使用此功能。周围没有很多例子。

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试这个

基于Selecting Data with pypika

的代码
from pypika import functions as fn

tbl = Table('thingsTable')
q = Query.from_(tbl).where(
    tbl.ID.isin(tbl.groupby(tbl.Car, tbl.Road, tbl.House).select(fn.Min(tbl.Id)))
).select(
    tbl.Id,tbl.Car,tbl.House,tbl.Road
).orderby(tbl.Id)