2012-09-28 34 views
3

我需要針對3種不同的狀態值編寫彙總報告,每種狀態都有一個計數和一個金額列,結果顯示在一張表中。例如,輸出應該是這樣的:我想編寫一個彙總查詢並將結果呈現在一個表中

enter image description here

以產生每行代碼(在一個單獨的輸出)該查詢是:

select case when status_key = '2' then 'Paid' else '' end as 'Status' 
, COUNT(BillNo) as [Count] 
, SUM(amtpd) as [Amount Paid] 
from billtable 
where client = 101 
and status_key = '2' 
group by status_key 

select case when status_key = '1' then 'Queued' else '' end as 'Status' 
, COUNT(BillNo) as [Count] 
, SUM(amtpd) as [Amount Paid] 
from billtable 
where client = 101 
and status_key = '1' 
group by status_key 

select case when status_key = '4' then 'Hold' else '' end as 'Status' 
, COUNT(BillNo) as [Count] 
, SUM(amtpd) as [Amount Paid] 
from billtable 
where client = 101 
and status_key = '4' 
group by status_key 

這產生三個結果一樣:

enter image description here

我使用SQL Server數據庫和SSMS發展查詢。

+2

爲什麼不使用UNION? – TlmaK0

+0

謝謝。我做了,當然它工作。 –

回答

5

不需要聯合。

使用WHERE只篩選所需的status_keys,然後展開CASE語句以從數字重新編碼爲單詞。

select 
    case when status_key = '2' then 'Paid' 
     when status_key = '1' then 'Queued' 
     when status_key = '4' then 'Hold' 
          else 'Error!' end  AS [Status], 
    COUNT(BillNo)         AS [Count], 
    SUM(amtpd)          AS [Amount Paid] 
from 
    billtable 
where 
    client = 101 
    AND status_key IN ('1','2','4') 
group by 
    status_key 

編輯使用維度表

select 
    status.description         AS [Status], 
    COUNT(bill_table.BillNo)        AS [Count], 
    SUM(bill_table.amtpd)         AS [Amount Paid] 
from 
    billtable 
inner join 
    status 
    on billtable.status_key = status.key 
where 
     bill_table.client  = 101 
    AND bill_table.status_key IN ('1','2','4') 
group by 
    status.description 

然後你可以有一個外鍵約束從statusbilltable變形例。這將確保數據不能插入billtable,除非status中有對應的密鑰。

您的查找將始終有效。但是如果status表未被正確填充,插入失敗的代價是「失敗」。

fact-tabledimension-table構建是關係數據庫設計的基礎。

+0

謝謝德姆。使用CASE的唯一困難是如果其中一個語句沒有值,我不會列出類別。 –

+1

@JerryC - 你應該真的有一個表格,可以將數值轉換爲單詞。但是,如果該查找表缺少相關行,該怎麼辦?這就是外鍵的用途。如果標識符不存在於維度表*(新的「狀態表」)*中,它將禁止事實表*('billtable')*中存在的數據。 – MatBailie

1

你就必須聯合所有

your first query 
Union all 
your Second query 
union all 
your third query 
+0

謝謝。當然,這工作得很好。 –

+0

@JerryC:不客氣.. –

0

只需將您的查詢之間添加UNION。

+0

謝謝。正如我在@TlmaK0評論中提到的那樣,我使用了Union並且它工作正常。由於某種原因,乍一看它逃脫了我。 –

+0

@Jerry C.在這種情況下,我強烈建議您使用Dems的解決方案,而不是UNION。它更整潔,更短,更容易維護等等,有一天你不會後悔的! –

+0

感謝您輸入@Vinny Roe。我會看看它,看看哪個最好。我繼續將每個原始查詢放在CTE中,以便在CTE上執行UNION。正如我想的那樣,我會把這個交給我的一個實習生,讓他們提出建議。 –

相關問題