所以我根据一张表撤回不同的account_ids,然后加入第二张表来汇总所述帐户的所有发票。
EX:account_id:1234567
假设有4张发票与1234567相关联,我正在总结这4张发票的数量并将其反映出去。
现在,我还想循环查看这4张发票,并检查其中的任何一张是否属于原始表格承诺中我'日期'后的90天内。
这是我所拥有的,但它不起作用,因为这只是抓取最近的发票,而我需要遍历所有这些以检查它是否为“新”(90天内没有发票)或' RECURRING'(这4张发票中的任何一张都在90天内)
这是我目前的代码:
SELECT
MIN(c.created_at) AS date,
c.meta_account_Id,
c.organization_Id,
c.user_id,
c.meta_distributorId,
c.meta_accountName,
sum( CASE WHEN s.invoice_date>=c.created_at
THEN coalesce(s.volumece,0)
ELSE 0
END ) AS ces,
CASE WHEN (max(s.invoice_date)) BETWEEN (adddays(MIN(c.created_at),-90)) AND (adddays(MIN(c.created_at),1))
THEN 'RECURRING'
ELSE 'NEW'
END AS type
FROM [commitments] c
LEFT JOIN [Sales2] s ON c.organization_Id=s.org_id AND
c.meta_account_Id=s.account_id
WHERE
c.status='active' AND
c.organization_Id='57aa010ae6125c0b007d241c' AND
c.user_id='598de688834ff20518a536d9'
GROUP BY
c.meta_account_Id,
c.organization_Id,
c.user_id,
c.meta_distributorId,
c.meta_accountName
答案 0 :(得分:0)
我接受它而不是知道MAX invoiceDate是否在90天内,这是:
CASE
WHEN (max(s.invoice_date)) BETWEEN
(adddays(MIN(c.created_at),-90)) AND (adddays(MIN(c.created_at),1))
THEN 'RECURRING'
ELSE 'NEW'
END AS type
您想要返回" RECURRING"如果任何相关的invoiceDate在90天内。这样做的方法(至少在我所知道的所有SQL版本中)都是使用EXISTS()函数:
CASE
WHEN EXISTS(SELECT * FROM Sales2 t1
WHERE t1.invoice_date BETWEEN
(adddays(MIN(c.created_at),-90)) AND (adddays(MIN(c.created_at),1))
AND c.organization_Id=t1.org_id AND
c.meta_account_Id=t1.account_id)
THEN 'RECURRING'
ELSE 'NEW'
END AS type