-1

我在 MySql 中有一张 MonthlySubscriber 表:

CREATE TABLE  MonthlySubscriber (
 MobileNo varchar(20) NOT NULL,
 Month int(11) NOT NULL,
 PRIMARY KEY (MobileNo, Month)
 );

一个手机号可以在一个多月内多次来电。所以根据手机号,我必须加入我的桌子。

要求:

我想自己加入我的桌子,只想要第一张桌子的 MobileNo 和 Month 以及第二张桌子的 Month。我想要(第一个表中所有 mobileNo 和月份的计数以及第二个表中的月份)与列中的 order by 和 group by(第一个表中的月份和第二个表中的月份)

我的 MySql 查询:

 Select COUNT(t.MSI), t.Mon1 ,t.Mon2 from
 ( SELECT
     MonthlySubscriber.MobileNo as MSI,
     MonthlySubscriber.Month as Mon1,
     MonthlySubscriber.Month as Mon2
   FROM MonthlySubscriber as MonthlySubscriber
   LEFT JOIN MonthlySubscriber as MonthlySubscriber on
         (MonthlySubscriber.MobileNo = MonthlySubscriber.MobileNo )
   ORDER by MonthlySubscriber.Month
 )
 t GROUP BY t.Mon1, t.Mon2;

我想要在休眠条件查询中完全相同的查询。

例子

桌子

> MobileNo  || Month 
> 852335421 || 1 
> 852335421 || 2 
> 852335421 || 5
> 994534554 || 3 
> 924443443 || 4 
> 994534554 || 7
> 864645353 || 1
result should come like this
>count_of_mobileNos || month 1 || month 2
>   2               ||  1       || 1
>   1               ||  1       || 2
>   1               ||  1       || 5
>   1               ||  2       || 2
>   1               ||  2       || 5
>   1               ||  3       || 3
>   1               ||  3       || 7
>   1               ||  4       || 4
>   1               ||  5       || 5
>   1               ||  7       || 7

注意月份是 1-12 的整数

4

1 回答 1

0

尝试这个:

SELECT count(MobileNo),
count( case when m.Month=1 then m.Month else 0 end ) as Month 1,
count( case when m.Month=2 then m.Month else 0 end ) as Month 2,
count( case when m.Month=3 then m.Month else 0 end ) as Month 3,
.
.
.
count( case when m.Month=12 then m.Month else 0 end ) as Month 12
FROM MonthlySubscriber m
GROUP BY m.Month
于 2013-07-24T02:00:02.517 回答