0

我有一个 MySQL 数据库,其中存储了某些商品的销售情况。我想比较过去两天的销售额,例如过去 10 天和过去 9 天。为此,我制定了 MySQL 查询:

select s1.sales - s2.sales from ProductSales as s1
left join ProductSales as s2 on s2.date >= DATE(DATE_ADD(Now(), INTERVAL '-10' DAY)) and s2.date <= DATE(DATE_ADD(Now(), INTERVAL '-9' DAY)) and s2.product_id = s1.product_id
where s1.date >= DATE(DATE_ADD(Now(), INTERVAL '-9' DAY));

我想在 Grails 应用程序中以编程方式执行此操作,并且需要将此查询转换为条件或 HQL 查询。我该怎么做?

更新:我试过这样:

def date1 = new Date() - 2
def date2 = new Date() - 1
def sales = ProductSales.executeQuery( """
    select s1.sales - s2.sales from ProductSales s1
    left join ProductSales s2
    where s1.date >= :date2
    and s2.date >= :date1 and s2.date < :date2 and s2.product_id = s1.product_id""",
[ date1: date1, date2: date2 ] )

不幸的是,这给了我:

ERROR hql.ast.ErrorCounter -  Path expected for join!
ERROR hql.ast.ErrorCounter -  Invalid path: 's2.sales'
ERROR hql.ast.ErrorCounter -  right-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter -  Invalid path: 's2.date'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter -  left-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter -  Invalid path: 's2.date'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter -  left-hand operand of a binary operator was null
ERROR hql.ast.ErrorCounter -  Invalid path: 's2.product_id'
ERROR hql.ast.ErrorCounter - <AST>:0:0: unexpected end of subtree
ERROR hql.ast.ErrorCounter -  left-hand operand of a binary operator was null
ERROR logging.impl.SLF4JLog - QuerySyntaxException occurred when processing request: [GET] /app/dashboard
Path expected for join!

更新 2:由于我无法回答我自己的问题,我在这里添加我的回复:

显然这可以正常工作:

def now = new Date()
def date1 = now - 2
def date2 = now - 1
def sales = ProductSales.executeQuery( """
    select s1.owner, s1.sales - s2.sales from ProductSales s1, ProductSales s2
    where s1.date >= :date2 and s1.date < :now 
    and s2.date >= :date1 and s2.date < :date2 and s2.product = s1.product""",
    [ date1: date1, date2: date2, now: now ]
    )

不过,我不完全确定 aleft join和 a之间有什么区别select from T1, T2now除此之外,我为最近的条目添加了一个上限 ( ) 并将其更改product_idproduct.

4

1 回答 1

0

显然这可以正常工作:

def now = new Date()
def date1 = now - 2
def date2 = now - 1
def sales = ProductSales.executeQuery( """
    select s1.owner, s1.sales - s2.sales from ProductSales s1, ProductSales s2
    where s1.date >= :date2 and s1.date < :now 
    and s2.date >= :date1 and s2.date < :date2 and s2.product = s1.product""",
    [ date1: date1, date2: date2, now: now ]
    )

不过,我不完全确定 aleft join和 a之间有什么区别select from T1, T2now除此之外,我为最近的条目添加了一个上限 ( ) 并将其更改product_idproduct.

于 2012-11-02T13:51:11.070 回答