2015-01-07 3 views
0

mysql 쿼리 또는 다른 결과 집합을 사용하는 두 개의 다른 쿼리를 작성하는 방법을 단일 테이블에 대해 하나의 배열로 변환 할 수 있습니까?하나의 테이블에 다른 조건과 결과가 설정된 두 개의 쿼리

나는이 하나의 테이블 t1 :

date   company  product  sales 
------------------------------------------------ 
2013-12-01  abc   a1   100 
2014-12-01  abc   b1   50 
2014-12-01  abc   c1   100 
2014-12-01  xyz   x1   100 

Query1 (based on selection of date='2014-12-01'): 
-------------------------------------------------------- 

select company, sum(sales) as day_sales from t1 where date='2014-12-01' 
group by company; 

will give: 

company day_sales 
--------------------------- 
abc  150 
xyz  100 

Query2 (based on selection of date between '2014-12-01' and '2013-12-31'): 
-------------------------------------------------------- 

select company, sum(sales) as previous_year_month_sale from t1 
where date between '2013-12-01' and '2013-12-31' group by company; 

will give: 

company previous_year_month_sale 
----------------------------------- 
abc  100 
내가 좋아하는 하나 개의 테이블에 두 결과를 결합 할 수있는 방법

:

company day_sales previous_year_mtd 
----------------------------------------- 
abc  150   100 
xyz  100   0 

제안하세요? 조회 한 결과를 루프

+1

POSS

$sales $row['company'][1] = $row['previous_year_month_sale'] ; 


출력 [MySQL 피벗 테이블]의 복제본 (http://stackoverflow.com/questions/7674786/mysql-pivot-table) – vaso123

+0

CASE 구문을 참조하십시오. – Strawberry

+0

https://dev.mysql.com/doc/refman/5.0/en/union.html – mudasobwa

답변

0
$sales = array(); 


이 추가 쿼리 2 결과 루프

$sales $row['company'][0] = $row['day_sales'] ; 


이것을 추가

foreach ($sales as $company => $val){ 
    echo "$company $val[0] $val[2] \n"; 
} 
+0

코드는 테스트되지 않았지만 작동해야합니다. 그렇지 않다면 일반적인 아이디어를 얻어야합니다. – Misunderstood

관련 문제