摆脱分组领域

时间:2016-08-02 21:11:34

标签: sql crystal-reports

在另一个字段中使用聚合时,是否有一种安全的方法可以不按字段分组?这是我的例子

SELECT 

C.CustomerName
,D.INDUSTRY_CODE

,CASE WHEN D.INDUSTRY_CODE IN ('003','004','005','006','007','008','009','010','017','029')
    THEN 'PM'
    WHEN UPPER(CustomerName) = 'ULINE INC'
    THEN 'ULINE'
    ELSE 'DR'
    END AS BU

,ISNULL((SELECT  SUM(GrossAmount) 
where CONVERT(date,convert(char(8),InvoiceDateID )) between DATEADD(yy, DATEDIFF(yy, 0, GETDATE()) - 1, 0) and DATEADD(year, -1, GETDATE())),0) [PREVIOUS YEAR GROSS]

FROM factMargins A 
LEFT OUTER JOIN dimDate B ON A.InvoiceDateID = B.DateId
LEFT OUTER JOIN dimCustomer C ON A.CustomerID = C.CustomerId
LEFT OUTER JOIN CRCDATA.DBO.CU10 D ON D.CUST_NUMB = C.CustomerNumber

GROUP BY 
C.CustomerName,D.INDUSTRY_CODE
,A.InvoiceDateID

order by CustomerName

在分组之前我只获得984行,但在通过A.InvoiceDateId字段分组后,我获得了超过11k行。由于每个客户有多个发票,因此行会爆炸。 Min和Max不会工作,因为它会错误地提取数据。让我的应用程序(水晶)摆脱多余的线条是最好的吗?通常,我希望尽可能让我的基础数据尽可能接近报告的布局方式。

1 个答案:

答案 0 :(得分:0)

尝试将对InvoiceDateID的引用移动到聚合函数中,而不是在选定的子查询的WHERE子句中。

在Oracle中,这是一个例子:

with TheData as (
select 'A' customerID, 25 AMOUNT , trunc(sysdate) THEDATE from dual union
select 'B' customerID, 35 AMOUNT , trunc(sysdate-1) THEDATE from dual union
select 'A' customerID, 45 AMOUNT , trunc(sysdate-2) THEDATE from dual union
select 'A' customerID, 11000 AMOUNT , trunc(sysdate-3) THEDATE from dual union
select 'B' customerID, 12000 AMOUNT , trunc(sysdate-4) THEDATE from dual union
select 'A' customerID, 15000 AMOUNT , trunc(sysdate-5) THEDATE from dual)
select 
    CustomerID, 
    sum(amount) as "AllRevenue" 
    sum(case when thedate<sysdate-3 then amount else 0 end) as "OlderRevenue", 
from thedata
group by customerID;

输出:

CustomerID | AllRevenue | OlderRevenue
A | 26070 | 26000
B | 12035 | 12000

这说:

  • 对于每个customerID
  • 我想要所有金额的总和
  • 我希望3天前的金额总和