2016-11-11 68 views
1

我有一個表,看起來像這樣排:如何另一列添​​加到SQL表基礎上組合在一起

DATE  ITEMS  CLASS  CATEGORY 
--------------------------------------------------------- 
2016-10-01 17915  Red   Apartment 
2016-10-01 39246  Red   Complex 
2016-10-01 4376  Blue  Apartment 
2016-10-01 12668  Blue  Complex 
2016-10-01 513   Yellow  Apartment 
2016-10-01 23271  Yellow  Complex 

我想通過類和計算到另一列添加到該表中組一個值作爲另一個的百分比。例如,在上述情況下,對於標記爲Class = Red的兩行,我希望將公寓類別中的項目值(17915)計算爲複雜項目中項目值的百分比(39246 ),達到49.64%,約爲50%。

所以查詢申請表上面應該產生看起來像這樣的輸出表:

DATE  ITEMS  CLASS  CATEGORY OCCUPANCY 
-------------------------------------------------------------------------- 
2016-10-01 17915  Red   Apartment 17915 * 100/39246 
2016-10-01 39246  Red   Complex  null 
2016-10-01 4376  Blue  Apartment 4376 * 100/12668 
2016-10-01 12668  Blue  Complex  null 
2016-10-01 513   Yellow  Apartment 513 * 100/23271 
2016-10-01 23271  Yellow  Complex  null 

不是那些操作,但實際值。這個查詢會是什麼樣子?我嘗試了GROUP BY子句的變體,但我想不出在分組之後會比較下一行的任何事情。

+0

mysql或sql-server? –

+0

sql server,對不起,額外的標記 – Freakishly

回答

1

你可以使用一個自連接和

select a.DATE, a.ITEMS, a.CLASS, a.CATEGORY, (a.ITEMS *100)/ b.ITEMS AS OCCUPANCY 
from my_table as a 
inner join my_table as b on a.class = b.classe 
wheer a.CATEGORY = 'Apartment' 
AND b.CATEGORY = 'Complex' 
UNION 
SELECT DATE, ITEMS, CLASS, CATEGORY, NULL 
FROM my_table 
where CATEGORY = 'Complex' 
+0

這工作完美,謝謝! – Freakishly

0

這是一種在MySQL中完成它的方法,假設每個Class總是有類別Apartment和Complex。

select ta.date,ta.items,ta.class,ta.category,ta.items*100.0/tc.items occupancy 
from t ta 
join t tc on ta.date=tc.date and ta.class=tc.class 
and ta.category='Apartment' and tc.category='Complex' 
union all 
select date,items,class,category,null 
from t 
where category='Complex' 

在SQL Server中,您可以使用窗口函數max來做到這一點。

select date,items,class,category, 
case when category = 'Apartment' then 
max(case when category='Apartment' then items end) over(partition by date,class)*100.0 
/max(case when category='Complex' then items end) over(partition by date,class) 
end as occupancy 
from t 
+0

謝謝,我應該澄清SQL服務器在我的問題。 – Freakishly

0

這個查詢作出一些假設一個工會。 1.你的類別將永遠是公寓和複雜。 2.這是SQL Server 2012(用sql server標記問題)。我不確定這是否適用於MySql。只是拋出一個選擇。

SELECT 
    DATE, 
    ITEMS, 
    CLASS, 
    CATEGORY, 
    (ITEMS * 100)/ LEAD(ITEMS) OVER (PARTITION BY CLASS ORDER BY CATEGORY) AS OCCUPANCY 
FROM Your_Table