Lyn*_*nie 5 sql t-sql sql-server
我有样本数据:: Data-Sample
Country Year Month CustID Sales Point TestSUM OrderType
Singapore 2018 10 AAA 623.96 520 1143.96 1
Singapore 2018 10 AAA 92.16 0 92.16 3
Singapore 2018 11 AAA 1168.28 1002.86 2171.14 1
Singapore 2018 11 BBB 118.58 103.25 221.83 1
Singapore 2018 10 CCC 118.88 103.25 222.13 1
Singapore 2018 11 CCC 278.67 217.75 496.42 1
Singapore 2018 11 CCC -108.72 -94.75 -203.47 2
Singapore 2018 11 CCC 0 0 0 3
Singapore 2018 10 DDD 446.14 385.9 832.04 1
Singapore 2018 11 DDD 138.95 121 259.95 1
Singapore 2018 11 DDD -228.07 0 -228.07 2
Singapore 2018 10 EEE 905.32 796.5 1701.82 1
Singapore 2018 10 EEE -405.75 -357.75 -763.5 2
Singapore 2018 10 EEE 29.66 0 29.66 3
Singapore 2018 11 EEE 147.8 127 274.8 1
Singapore 2018 10 FFF 0 0 0 3
Singapore 2018 10 GGG 0 0 0 3
Singapore 2018 10 HHH 120.57 104.5 225.07 1
Singapore 2018 10 HHH 0 0 0 3
Singapore 2018 11 HHH 189.59 165.25 354.84 1
Singapore 2018 10 JJJ 117.12 100.25 217.37 1
Singapore 2018 10 JJJ 0 0 0 3
Singapore 2018 11 JJJ 291.53 254.25 545.78 1
Run Code Online (Sandbox Code Playgroud)
我试图根据3个列中的2个标准计算不同的'CustID':
因此,我创建了一个额外的列'TestSUM',它将'Sales'和'Points'相加,它们不等于0,以满足标准#1
使用下面的代码,我可以根据我的标准#1执行不同的CustID计数时排除CustID FFF和GGG:
Select
Country
, o.Year
, o.Month
, sum(o.Sales)
, sum(o.Points)
, sum(o.Sales + o.Points) as 'TestSUM'
, o.OrderType
From FactOrders O
Join CustTable as C on o.CustID = c.CustID
and o.OrderType in (1,2,3)
Group by
Country
, o.Year
, o.Month
, o.OrderType
, c.CustID
having sum(o.Sales + o.Points) <> 0
Order by
c.CustID
Run Code Online (Sandbox Code Playgroud)
但是,我希望我的结果看起来像是这样的:
Country Year Month Distinct Count Sales
Singapore 2018 10 6 2048.06
Singapore 2018 11 7 1996.61
Run Code Online (Sandbox Code Playgroud)
如何修改我的脚本以删除"CustID","Point","TestSUM","OrderType"列,但仍保留反映标准的独特计数
having sum(o.Sales + o.Points) <> 0
Run Code Online (Sandbox Code Playgroud)
评论详情:
我希望每个客户应用sales + points <> 0条件,但当我从group中删除CustID,Point,TestSum和OrderType并且选择时,结果返回到CustID不显示行,sales + points <> 0条件没有不再适用于每个客户...... CustID的独特数量将包括销售额+点数> 0的行数
也许你可以像下面这样做。请注意,我删除了 CustTable 的 JOIN,因为它没有被使用。如果 FactOrders 和 CustTable 之间没有引用完整性,您可以保留它。
我将您的必须移动到您正在计算客户的位置,即使他们有一行是 0 和 0。
Select
Country=o.Country
,Year= o.Year
,Month= o.Month
,[Distinct Count]=Count(distinct custid)
,Sales= sum(o.Sales)
From FactOrders O
where
o.OrderType in (1,2,3) and (o.Sales<>0 or o.Points<>0)
Group by
o.Country, o.Year, o.Month
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
115 次 |
最近记录: |