2013-07-14 25 views
-1

我有鑑於這給合理正確答案:管理數據庫,以便獲得正確的結果

DELIMITER $$ 

DROP VIEW IF EXISTS `test`.`new_temp`$$ 

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `new_temp` AS 
SELECT `temp`.`pcount` AS `ind_type`,SUM(`temp`.`pcount`) AS `Index_val` FROM `temp` UNION ALL 
SELECT `temp`.`ncount` AS `sum`,SUM(`temp`.`ncount`) AS `ncount` FROM `temp` $$ 

DELIMITER ; 

輸出繼電器:

ind_type Index_val 
---------------------- 
2    23 
2    34 

我希望它給這個還挺輸出:

New_temp 

    ind_type  Index_val 
------------------------------- 
    pcount   23 
    ncount   34 

問題出在我寫的代碼上。我嘗試了不同的方式,但我沒有得到它。任何想法?

回答

1

你正在嘗試獲得的,而不是它的值的列的實際名稱。在這種情況下,而不是說

SELECT `temp`.`pcount` AS `ind_type` 

做到像

SELECT 'pcount' AS `ind_type` 

編輯:

不知道你是什麼給予​​同樣的結果意味着什麼。我試了一樣,它工作正常;如下

create table temp (pcount int,ncount int); 

insert into temp values(22,33); 

insert into temp values(23,43); 


create VIEW new_temp as 
select 'pcount' AS 'ind_type',sum(pcount) as 'ind_val' 
from temp 
union 
select 'ncount' AS 'ind_type',sum(ncount) as 'ind_val' 
from temp; 

檢查這個SQL小提琴http://sqlfiddle.com/#!2/bbcf6/1

+0

它給出了相同的結果!不用找了! – user123

+1

@卡里姆汗,看我的編輯。 – Rahul

+0

非常感謝@Rahul。我用這個愚蠢的錯誤來代替pcount和ncount。所以它給出了pcount和ncount的第一個值,而是將它看作行名! – user123

1

通常情況下,您將在標準化字典表或類似字段中獲取值。但是由於您在查詢中沒有提供任何內容,因此以下內容應該會給出所需的結果。

SELECT 'pcount' AS `ind_type`,SUM(`temp`.`pcount`) AS `Index_val` FROM `temp` UNION ALL 
SELECT 'ncount' AS `ind_type`,SUM(`temp`.`ncount`) AS `ncount` FROM `temp` $$ 
+0

它給了相同的結果!不用找了! – user123

+1

它是否在'ind_type'列的兩行中給出結果'2'? – 2013-07-14 12:03:46

+0

是的,它爲什麼在兩行上都給出了兩個1 – user123

相關問題