0

我正在尝试编写等效的 SQL 查询:

SELECT tax.name as tax, SUM(item.cost * item.amount) as total FROM Invoices inv
JOIN InvoiceItems item ON( item.invoice = inv.id )
JOIN Taxes tax ON( tax.id = it.tax )
WHERE inv.id = 1
GROUP BY tax.id

我不知道如何在查询中“添加”总列,我的代码如下

val res = Invoices
            .innerJoin(InvoiceItems, { Invoices.id }, { InvoiceItems.invoice })
            .innerJoin(Taxes, { InvoiceItems.tax }, { Taxes.id })
            .slice( Taxes.name.alias("tax"), InvoiceItems.cost, InvoiceItems.amount )
            .select { Invoices.id eq 1 }

甚至可以这样做还是我必须稍后在代码中这样做?

4

2 回答 2

1

您可以在块内使用 TimesOp Expression.build{},如下所示:

    val total = Expression.build { Invoices.cost * Invoices.amount }
    val taxAndTotal = Invoices.innerJoin(InvoiceTaxes).innerJoin(Taxes)
        .slice(Taxes.name, total)
        .select{ Invoices.id eq 1 }
        .groupBy(Taxes.id)
        .map { it[Taxes.name] to it[total] }
于 2019-04-21T18:21:27.563 回答
0

我没有找到我们如何使用timeslike InvoiceItems.cost times InvoiceItems.amount,但是您可以像这样构造自己的TimesOp对象:

val taxAlias = Taxes.alias("tax")
val itemAlias = InvoiceItems.alias("item")
val invoiceAlias = Invoices.alias("inv")
println(invoiceAlias
        .innerJoin(itemAlias, { invoiceAlias[Invoices.id] }, { itemAlias[InvoiceItems.invoice] })
        .innerJoin(taxAlias, { itemAlias[InvoiceItems.tax] }, { taxAlias[Taxes.id] })
        .slice(
                taxAlias[Taxes.name].alias("tax"),
                TimesOp(
                        itemAlias[InvoiceItems.cost],
                        itemAlias[InvoiceItems.amount],
                        InvoiceItems.amount.columnType
                ).sum().alias("total"))
        .select { invoiceAlias[Invoices.id] eq 1 }
        .groupBy(taxAlias[Taxes.id])
        .prepareSQL(QueryBuilder(false))
)

为 h2 语法输出以下 sql:

SELECT TAX.NAME tax, SUM((ITEM.COST) * (ITEM.AMOUNT)) total FROM INVOICES inv
INNER JOIN INVOICEITEMS item ON INV.ID = ITEM.INVOICE 
INNER JOIN TAXES tax ON ITEM.TAX_ID = TAX.ID 
WHERE INV.ID = 1 
GROUP BY TAX.ID
于 2019-04-21T15:39:34.380 回答