我有2个查询,已使用UNION比较了2年中每个客户的销售额。下面返回两列,一列用于组织,一列用于销售价值/客户。但是2年的拆分无效。似乎将所有值都拉到一列中,而不是将2018年和2019年作为一列。也许我应该使用联接或子查询?
返回结果类似于:
Organization Last Year Previous year
CUS 12000 160000
etc
SELECT Top 25
FORMAT(SUM(dbo.ARInvoices.arpFullInvoiceSubtotalBase), 'C2') AS "previousyear ", dbo.Organizations.cmoOrganizationID AS "Organization"
FROM (dbo.ARInvoices
LEFT OUTER JOIN dbo.Organizations ON dbo.ARInvoices.arpCustomerOrganizationID = dbo.Organizations.cmoOrganizationID)
WHERE YEAR(arpInvoiceDate) = year(DATEADD(year, -2, getdate()))AND arpInvoiceType = 1
GROUP BY dbo.Organizations.cmoOrganizationID
UNION
SELECT Top 25
FORMAT(SUM(dbo.ARInvoices.arpFullInvoiceSubtotalBase), 'C2') AS "Lastyear", dbo.Organizations.cmoOrganizationID AS "Organization"
FROM (dbo.ARInvoices
LEFT OUTER JOIN dbo.Organizations ON dbo.ARInvoices.arpCustomerOrganizationID = dbo.Organizations.cmoOrganizationID)
WHERE YEAR(arpInvoiceDate) = year(DATEADD(year, -1, getdate()))AND arpInvoiceType = 1
GROUP BY dbo.Organizations.cmoOrganizationID'
答案 0 :(得分:0)
您可以进行条件聚合
select
sum(case
when arpInvoiceDate >= datefromparts(year(getdate()) - 2, 1, 1)
and arpInvoiceDate < datefromparts(year(getdate()) - 1, 1, 1)
then i.arpFullInvoiceSubtotalBase
end) as previousYear,
sum(case
when arpInvoiceDate >= datefromparts(year(getdate()) - 1, 1, 1)
then i.arpFullInvoiceSubtotalBase
end) as lastYear
from dbo.ARInvoices i
inner join dbo.Organizations o ON i.arpCustomerOrganizationID = o.cmoOrganizationID
where arpInvoiceType = 1 and arpInvoiceDate >= datefromparts(year(getdate()) - 2, 1, 1)
group by o.cmoOrganizationID
注意:
我使用INNER JOIN
代替了LEFT JOIN
,因为GROUP BY
子句中使用了左表的一列
表别名的确使查询更短,更易于阅读
我更改了日期过滤的实现,因此在表列上不使用日期功能(这使查询效率更高)