2016-12-20 78 views
2

我有一個包含以下行數據的表。將行與單個SQL Server中的另一行進行比較表

EngID Tower Billing Amt 
100  ICS  Y  5000 
100  EDT  Y  7777 
100  ICS  N  2000 

和我想要的結果設置爲通過塔&主機ID和投入相應的列的數量被合併基於結算標準(發票金額或不開發票)。所以,下面是最終的結果集應該是什麼樣子的上表:

EngID Tower Inv Amt (Amt when Billing = Y) Non-Invoiced Amt (Billing=N) 
100  ICS  5000          2000 
100  EDT  7777 

我能夠得到的結果通過使用下面的查詢中設置的第1行:

Select Temp1.Tower, Temp1. EngID, Temp2.InvoiceAmt as [Inv Amt], Temp1.InvoiceAmt AS [Non-Invoiced Amt] from 
(
SELECT EngID, TOWER,BILLING, InvoiceAmt,RANK() OVER (PARTITION BY EngID, TOWER ORDER BY BILLING) AS RNK 
    FROM [GDF].[dbo].[Sample] ) Temp1 INNER JOIN (SELECT EngID, TOWER,Billing,InvoiceAmt, RANK() OVER (PARTITION BY EngID, TOWER ORDER BY BILLING) AS RNK 
    FROM [GDF].[dbo].[Sample]) Temp2 ON 

    Temp1.EngID = Temp2.EngID 
    AND (Temp1.Tower = Temp2.Tower AND Temp1.Billing < Temp2.Billing) 

然而,努力獲得第二排結果。我的計劃是通過兩個單獨的查詢獲得兩行,然後進行聯合以合併結果。

回答

2

一種方法是有條件聚集:我們也可以不使用OUTER它

select s.engid, s.tower, 
     sum(case when s.billing = 'Y' then amt end) as billing_y, 
     sum(case when s.billing = 'N' then amt end) as billing_n 
from gdf.dbo.sample s 
group by s.engid, s.tower; 
+0

這是什麼'gdf.dbo'是什麼意思? –

+0

這是SQL Server中使用的三分命名約定。 –

1

試試這個:

select engid, tower, 
    sum(case when billing = 'Y' then amt end) Inv_amt, 
    sum(case when billing = 'N' then amt end) Non_Inv_amt, 
from my_table 
group by 
    engid, 
    tower; 
0

適用如下:

select A.EngID, 
    sum(A.Amt) as [Inv Amt (Amt when Billing = Y)], 
    sum(B.Amt) as [Non-Invoiced Amt (Billing=N)] 
from #test A 
outer apply(select b.Amt from #test B where A.EngID = b.EngID and b.tower = a.tower and B.Billing = 'n') B 
where a.billing = 'y' 
group by A.EngID, A.Tower 

簡單LEFT JOIN:

select A.EngID, 
    sum(A.Amt) as [Inv Amt (Amt when Billing = Y)], 
    sum(B.Amt) as [Non-Invoiced Amt (Billing=N)] 
from #test A 
left join #test B on A.EngID = b.EngID 
    and b.tower = a.tower 
    and B.Billing = 'n' 
where a.billing = 'y' 
group by A.EngID, A.Tower 
0

此代碼將給出所需的結果沒有任何複雜性。請從下面提到的查詢找到輸出的快照。希望我解決了您的問題。 enter image description here

WITH Mycte 
AS 
(
Select ENGID,Tower,Case When Billing='Y' Then ISNULL(SUM(Amt),0) END AS Inv_Amt, 
Case When Billing='N' Then ISNULL(SUM(Amt),0) END AS Non_Inv_Amt from #Sample 
group by ENGID,Tower,Billing 
) 
Select ENGID,Tower,SUM(Inv_Amt) AS Inv_Amt,SUM(Non_Inv_Amt) AS Non_Inv_Amt from mycte 
group by ENGID,Tower 
相關問題