|
我有一个查询,看起来像这样:
3 H* v' A$ R sSELECT OrganizationName,OrganizationID,ReceivableStatus,InvoiceFeeFROM v_InvoicesFreelanceOutstandingORDER BY OrganizationID这些数据可能看起来像这样:
1 \( {" ~7 Q, ]6 {9 @) VOrganizationName OrganizationID ReceivableStatus InvoiceFee-----------------------------------------------------------------------------Company A 6000 -90 days .00Company A 6000 -90 days .00Company A over 90 days .00Company B Current .38Company B 60-90 days .50Company C 6000 -90 days .25Company C over 90 days .50Company C over 90 days .25我最后想展示的是这样的(以上数据):
3 L8 n0 n. ^2 k+ [, ~( y) P5 U9 xCompany Current 30-60 days 60-90 days over 90 days Total -----------------------------------------------------------------------------Company A .000 00 .00Company B 3559. 385555 .5050 .88Company C .25 17633.75 2210.00我的SQL-fu不足以让我超越这个范围:) c4 r# b+ d( o/ v x
SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDueFROM v_InvoicesFreelanceOutstandingGROUP BY OrganizationID,ReceivableStatus以上内容(同样,上述数据)显示:0 o9 a. {' Q0 g- |# r3 }
OrganizationName OrganizationID ReceivableStatus TotalDue-----------------------------------------------------------------------------Company A 6000 -90 days .00Company A over 90 days .00Company B Current .38Company B 60-90 days .50Company C 6000 -90 days .25Company C over 90 days .75那怎么样?任何帮助,都将不胜感激。' o" Y3 {9 W |5 C6 Z) o3 D" t
需要注意的是,第二表所示的状态(Current,30-60 days,60-90 days,over 90days)是我唯一期待拿出来的ReceivableStatus。
$ }9 l8 S$ t, C7 W6 t- m8 }编辑 :对不起,不包括这个。我知道,PIVOT但我无法让它做我想做的事。
, D5 A' N+ i* h: h: Y/ D3 j6 t
; `5 Y# E; i0 V6 {4 Q# t8 } 解决方案: ( {$ U: U; G3 j7 y$ M6 u
pivot假如你用的是SQL1 l- ^ T0 y% U7 o* m: L
Server 2005或更高的版本看起来像工作。2 D R. \' I9 Z$ ^# P1 a
编辑:8 j) k! H2 q! A* G9 s
既然你已经知道了pivot,你会知道它几乎能满足你的需求。' N. M B3 D) y) c2 B u
您已有以下查询:4 x9 Z) K' v' g0 B9 m# `: R
SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDueFROM v_InvoicesFreelanceOutstandingGROUP BY OrganizationID,ReceivableStatus这可以为您提供当前需要的30-60、60-90和90 零件。如果你这样做了,你将得到你需要的一切,除了总数。因此,只需总投资:
* `$ ]+ t6 O: v8 `. K2 d5 y4 Z; o(SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, ReceivableStatus, SUM(InvoiceFee) as TotalDueFROM v_InvoicesFreelanceOutstandingGROUP BY OrganizationID,ReceivableStatus)UNION(SELECT MAX(OrganizationName) as OrganizationName, OrganizationID, 'Total' AS ReceivableStatus, SUM(InvoiceFee) as TotalDueFROM v_InvoicesFreelanceOutstandingGROUP BY OrganizationID)透视此结果,您将获得所需的输出: w# O- j- ~1 I9 L6 G; l
SELECT *FROM [the query above]PIVOT SUM(TotalDue) FOR ReceivableStatus IN ([Current],[30-60 days],[60-90 days],[over 90 days],[Total]) ) |
|