2016-11-11 63 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