2012-07-11 73 views
0

我有兩個查詢加入union All聯盟ALL取空行

SELECT select 'Finished' AS Status,amount AS amount,units As Date 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
SELECT select 'Live' AS Live,amount,units 
from table1 Where Pdate = cdate And name [email protected] 

結果

Status  amount units 
Finished  100 20 
Live   200 10 

當任一查詢取空集,我只得到一個行,如果兩者取空集,然後我沒有行

所以,我怎樣才能得到像這

Status  amount Units 
Finished  100 20 
Live   0  0 

OR

Status  amount Units 
Finished  0  0 
Live   200 10 

OR

Status  amount Units 
Finished  0   0 
Live   0   0 

感謝。

+2

您選擇單位的日期和「活」的活。這不應該是單位作爲單位和「現場」狀態? – Dan 2012-07-11 12:41:40

回答

1

我會認爲你可以使用總和?如果總和不返回0時沒有行然後用Coalesce(sum(amount), 0) as amount

SELECT select 'Finished' AS Status,sum(amount) AS amount, sum(units) As Unit 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
SELECT select 'Live' AS Status, sum(amount) as amount, sum(units) as Unit 
from table1 Where Pdate = cdate And name [email protected] 

更換,如果你是不是想總結的結果那麼就應該合併工作? coalesce(amount, 0) As amount等...

+0

您可能需要在「SELECT」語句中使用「GROUP BY」。 – 2012-07-11 12:43:38

+0

我不這麼認爲......我假設他想總結所有的記錄。 – Dan 2012-07-11 12:46:31

+0

+1,OP希望顯示兩行,而不管每個分支中合格記錄的數量(0..n)。但我認爲OP希望空值顯示爲零。 – 2012-07-11 13:10:44

0

我只想指出,你的查詢是不必要的複雜,嵌套選擇和聯合所有。編寫查詢的更好方法是:

select (case when pdate > cdate then 'Finished' else 'Live' end) AS Status, 
     amount AS amount, units As Date 
from table1 
WHERE Pdate >= cdate AND name = @name 

此查詢不會生成您想要的內容,因爲它只生成有數據的行。

獲取附加行的一種方法是增加原始數據,然後檢查是否需要。

select status, amount, units as Date 
from (select Status, amount, units, 
      row_number() over (partition by status order by amount desc, units desc) as seqnum 
     from (select (case when pdate > cdate then 'Finished' else 'Live' end) AS Status, 
        amount, units, name 
      from table1 
      WHERE Pdate >= cdate AND name = @name 
      ) union all 
      (select 'Finished', 0, 0, @name 
      ) union all 
      (select 'Live', 0, 0, @name 
      ) 
     ) t 
where (amount > 0 or units > 0) or 
     (seqnum = 1) 

這增加了你想要的額外行。然後列舉它們,所以它們會以任何順序走到最後。它們被忽略,除非它們是序列中的第一個。

0

嘗試這樣的事情

with stscte as 
(
select 'Finished' as status 
union all 
select 'Live' 
), 
datacte 
as(
select 'Finished' AS Status,amount AS amount,units As Date 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
select 'Live' ,amount,units 
from table1 Where Pdate = cdate And name [email protected] 
) 
select sc.status,isnull(dc.amount,0) as amount,isnull(dc.unit,0) as unit 
from stscte sc left join datacte dc 
on sc.status = dc.status