2016-03-29 30 views
0

Bir table1 var:farklı sütun adları ve aynı satırlarla iki tablo Üyelik

|age | name | sex | money | 
------------------------------- 
|20 | James | 1 | 1000 | 
|20 | Marry | 2 | 2000 | 
|20 | Kate | 2 | 1500 | 
|20 | Parker | 1 | 1800 | 

Ve iki sorgu sonuçları:

1:

select `age`, count(*) as `man`, sum(money) as man_money 
from table1 
where `sex` = 1 and age = 20; 

|age| man | man_money | 
------------------------- 
|20 | 2  | 2800  | 

2:

select `age`, count(*) as `woman`, sum(money) as woman_money 
from table1 
where `sex` = 2 and age = 20; 

|age |woman | woman_money | 
----------------------------- 
|20 |2  | 3500  | 

r'yi birleştirmek istiyorum bunun gibi esastlar:

|age | man | woman | man_money | woman_money | 
-------------------------------------------------- 
|20 | 2  | 2  | 2800  | 3500  | 

SQL nasıl yazılır?

cevap

0

bu deneyin:

select age, 
     count(case when sex = 1 then 1 end) as man, 
     count(case when sex = 2 then 1 end) as woman, 
     sum(case when sex = 1 then money end) as man_money, 
     sum(case when sex = 2 then money end) as woman_money 
from table1 
where age = 20 
+0

sayesinde, bu ihtiyaç olarak çalışıyor kahin bu çalıştı ~ çalışır ancak iki sonuca doğrudan katılmanın herhangi bir yolu var mı? Bazı sütunlar SUM() yöntemini kullanması gerektiğinden, – teejoe

+0

@teejoe Sorunun iki sorgusunu oldukları gibi birleştirmek istersiniz? –

+0

*** @ teejoe ***: Bir sorguda birden fazla kez * 'case' * kullanabilir ve *' sum' ile birleştirebilirsiniz * ... –

0

benim bilgi sql tüm DB için aynıdır Mysql hakkında, ancak bilmiyorum, ben size

select age, 

     count(case when sex = 1 then 1 end) as man, 

     count(case when sex = 2 then 1 end) as woman 

from table1 group by age; 
İlgili konular