2013-12-12 39 views
0

我有這個select語句。我知道我可以用一個聯盟來解決這個問題,但我被告知效率不高,我的老闆們要求我在單個查詢中完成,而不是使用聯盟,因爲它使用同一張表。這是有道理的。具有相同名稱和數據類型但合併函數結果的SQL合併2 Colums

select 
'No Photos' as 'Type', 
    SUM(case when Cntimagedata < 12 or cntimagedata is null then 1 else 0 end) as  Value, 
'Incomplete Photos' as 'Type', 
    SUM(case when Cntimagedata < 12 then 1 else 0 end) as Value 
    from tablemain 

查詢生成下表。


'類型'| '價值'| '類型'| 'Value'

沒有照片| 15 |不完整的照片| 3


但我的答案必須


'類型' ----------------- | ---- '值'

沒有照片------------ | 15

不完整的照片 - | 3


只有2列而不是4 ...這可能嗎?我一直在試圖讓這個解決方案起作用。並且連接不符合這個(我認爲),因爲它需要的所有數據都在這張表中。

我不能像前面提到的那樣使用Union,因爲我的老闆們說我正在使查詢變慢。

回答

1
SELECT 'No Photos' as 'Type', SUM(case when Cntimagedata < 12 or cntimagedata is null then 1 else 0 end) as  Value 
FROM tablemain 
UNION SELECT 'Incomplete Photos' as 'Type', SUM(case when Cntimagedata < 12 then 1 else 0 end) as Value 
FROM tablemain 

或者因爲你現在可以把在WHERE子句

SELECT 'No Photos' as 'Type', count(cntimagedata) Value 
FROM tablemain where Cntimagedata < 12 or cntimagedata is null 
UNION SELECT 'Incomplete Photos' as 'Type', count(cntimagedata) Value 
FROM tablemain where Cntimagedata < 12 
+0

感謝您的答覆@vittore,但我不能,因爲它減慢我的查詢,我的上司要我解決了使用聯盟條件它以任何其他方式因此。 –

+0

減速最有可能意味着您沒有使用正確的索引。 – vittore

+0

數據正在被唯一鍵索引。有什麼其他方式可以索引它嗎?所以你說聯盟不一定是表現放緩?我知道它不會像光標那樣慢。 –

相關問題