以下是该方案:
只是解释一下,代码和名称密钥属于Table1 paymentDate,金额密钥在Table2上,但它们共享外键的uniqueId密钥。
预期结果应该像这样结束:
[{
"code": 1011,
"name": "Customer1",
"amount": 5000,
"paymentDate": "2016-10-20T04:00:00.000Z"
"paymentDate": "2016-11-20T04:00:00.000Z"
"paymentDate": "2016-12-20T04:00:00.000Z"
},
{
"code": 1012,
"name": "Customer2",
"amount": 5000,
"paymentDate": "2016-03-20T05:00:00.000Z"
"paymentDate": "2016-04-20T05:00:00.000Z"
"paymentDate": "2016-05-20T05:00:00.000Z"
"paymentDate": "2016-06-20T05:00:00.000Z"
},
{
"code": 1013,
"name": "Customer3",
"amount": 5000,
"paymentDate": "2016-01-20T05:00:00.000Z"
"paymentDate": "2016-02-20T05:00:00.000Z"
}]
到目前为止我有这个:
SELECT coreObjects.code,
coreObjects.name,
lateobjectpayments.amount,
lateobjectpayments.paymentDate
FROM coreObjects
JOIN lateobjectpayments
ON coreObjects.uniqueId=lateobjectpayments.uniqueId
GROUP BY YEAR(lateobjectpayments.paymentDate)
似乎我需要在连接附近进行多选,但到目前为止还没有我想要的东西。如果有人可以帮助我,我将不胜感激。
答案 0 :(得分:0)
问题在于,您不能通过聚合(将几个原始元组合并为一个结果元组)和单个group by语句中的详细信息选择(需要所有原始元组)进行组合。
如果您使用子句GROUP BY YEAR(lateobjectpayments.paymentDate)
编写查询,那么结果将包含每年最多一个元组,并且只有一个客户和paymentDate与这样的结果元组相关联。
因此,将查询拆分为子查询;一个用于获取每amount
和uniqueId
的汇总值(即year
),另一个用于“获取”详细信息:
select c.*, aggr.amount, lop.*
from (select uniqueId, year(paymentDate) as year, sum(amount) as amount from
lateobjectpayments
group by uniqueId, year(paymentDate)) aggr
join coreObjects c on c.uniqueId = aggr.uniqueId
join lateobjectpayments lop on year(lop.paymentDate)=aggr.year and lop.uniqueId = aggr.uniqueId
请注意,sql结果是表格形式,而不是半结构化,例如json。但是,从您选择的任何编程语言中以表格形式导出半结构化表单应该很容易。