总计发票的份额(总和除以)

时间:2013-10-25 15:00:37

标签: sql group-by sum

我有销售线,其中一些是开发票,有些则没有。我想添加每个订单(salesid)的发票行份额信息。我希望每个销售线的这些信息在一个订单中是相同的。已开票行的销售状态= 3。这是我的尝试:

SELECT  
salesid,linenum,itemid,salesstatus,name,lineamount
,(SELECT SUM(CASE WHEN salesstatus=3 THEN lineamount ELSE 0 END) as expr1) invoiced
,(SELECT SUM (lineamount) as expr2 GROUP BY salesid) total
,invoiced/total
FROM T.SALESLINES 
GROUP BY
salesid,linenum,itemid,salesstatus,name,lineamount

按salesid分组不起作用,给出错误“每个GROUP BY表达式必须包含至少一个不是外部引用的列。” 我想这些代码似乎合乎逻辑但不起作用。那么我应该如何按照salesid对发票进行分组?

1 个答案:

答案 0 :(得分:0)

尝试

Select *,invoiced/total as ColName from (
SELECT  
salesid,linenum,itemid,salesstatus,name,lineamount
,(SELECT SUM(CASE WHEN salesstatus=3 THEN lineamount ELSE 0 END From T.SALESLINES) as invoiced
,(SELECT SUM (lineamount)From T.SALESLINES GROUP BY salesid) as total
FROM T.SALESLINES) source
GROUP BY
salesid,linenum,itemid,salesstatus,name,lineamount,invoiced,total