首页 > 解决方案 > Group by with Inner join 不返回任何结果

问题描述

SELECT TOP 6 *
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

如您所见,我有一个根据客户帐号与该表vws_entryline关联的表。vws_customer我想按另一个字段VoucherNumbervws_entryline仅存在于其中)对结果进行分组。

例如,我想要这些结果(它不是 JSON 格式,只是我脑海中的一个示例,它与 group by 不完全对应......但我想要的实际上是一个 SQL group by 结果):

{AccountNumber:“PO200”,field_1_vws_customer:“foo”,GeneralAccountNumber:“PO200”,“VoucherNumber”:“N45PO”,field_1_vws_entryline:150.25},

{AccountNumber:“PO200”,field_1_vws_customer:“foo”,GeneralAccountNumber:“PO200”,“VoucherNumber”:“N45PO”,field_1_vws_entryline:25.75},

{AccountNumber:“PO200”,field_1_vws_customer:“foo”,GeneralAccountNumber:“PO200”,“VoucherNumber”:“AZERTY”,field_1_vws_entryline:50,50},

{AccountNumber:“SW7”,field_1_vws_customer:“foo”,GeneralAccountNumber:“SW7”,“VoucherNumber”:“42HaveAGoodDay24”,field_1_vws_entryline:50,50}

如您所见,结果按VoucherNumber字段正确分组。

但是,我的 SQL 请求没有返回任何结果。为什么?

编辑

我试过了:

SELECT el.EntryLineDate, el.VoucherNumber, el.label, el.GeneralAccountNumber,
       el.Debit, el.Credit, el.type, el.amount, el.PaymentTypeid, el.EntryNumber,
       c.ThirdId, c.civility, c.name, c.NaturalPerson, c.ThirdLanguage, c.siren,
       c.nic, c.naf, c.AccountNumber
from vws_entryline el
inner join vws_customer c on el.GeneralAccountNumber = c.AccountNumber
group by el.VoucherNumber

但它不起作用

标签: sqlsql-server

解决方案


您没有汇总 JSON 结果集中的凭证编号。它显示为一个普通的 JSON 文档,每一行对应每个凭证号。

由于您没有提供架构,以下是粗略查询。您需要使用 FOR JSON 子句来实现 JSON 结果集。阅读更多关于 FOR JSON

SELECT v_c.AccountNumber, field_1_vws_customer,GeneralAccountNumber, 
VoucherNumber, field_1_vws_entryline
FROM vws_entryline AS v_e
JOIN vws_customer AS v_c
ON v_e.accountNumber = v_c.accountNumber
FOR JSON PATH;

推荐阅读