簡體   English   中英

將單個SQL Server表中的行與其他行進行比較

[英]Comparing rows with another rows in a single SQL Server Table

我有一個包含以下幾行數據的表。

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

並且我希望根據Tower&Eng ID合並結果集,並根據“結算”標准將金額放入相應的列(“已開具發票”或“未開具發票”)中。 因此,以下是最終結果集應如何查找上表的內容:

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

我可以使用以下查詢獲取結果集的第一行:

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) 

但是,努力獲得第二行結果。 我的計划是通過兩個單獨的查詢獲取兩行,然后進行合並以合並結果。

一種方法是條件聚合:

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;

嘗試這個:

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;

我們還可以使用OUTER APPLY來做到這一點,如下所示:

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

簡單的左聯接:

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

這段代碼將提供所需的結果而沒有任何復雜性。請務必從下面提到的查詢中找到輸出的快照。希望我解決了您的問題。 在此處輸入圖片說明

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM