select (case when c.billcycle>c.firstzm then c.billcycle else c.firstzm end )as firstzm,c.thirdzm,c.secondzm
from
(select *
from (
select cast(month(billcycle) as char)as billcycle,cast(count(month(billcycle)) as char) as thirdzm
from tb_ac_billpaid_yym
where
(select month(billcycle))>(select month(now())-4) and (select month(billcycle))<=(select month(now()))
group by cast(month(billcycle) as char)) as a
right join
(select cast(month(billcycle) as char)as firstzm,cast(count(month(billcycle)) as char) as secondzm
from tb_ac_billunpaid
where
(select month(billcycle))>(select month(now())-4) and (select month(billcycle))<=(select month(now()))
group by cast(month(billcycle) as char)) as b
on a.billcycle=b.firstzm)
as c
對於我這樣乙個菜鳥我都佩服我能寫出這樣的sql語句。
下面我來解釋一下我的這段sql語句的意思:
首先分別從兩個表中查出自己需要的資料:
(1)
select cast(month(billcycle) as char)as billcycle,cast(count(month(billcycle)) as char) as thirdzm
from tb_ac_billpaid_yym
where
(select month(billcycle))>(select month(now())-4) and (select month(billcycle))<=(select month(now()))
group by cast(month(billcycle) as char)
(2)select cast(month(billcycle) as char)as firstzm,cast(count(month(billcycle)) as char) as secondzm
from tb_ac_billunpaid
where
(select month(billcycle))>(select month(now())-4) and (select month(billcycle))<=(select month(now()))
group by cast(month(billcycle) as char)
這兩段sql有異曲同工之處,就是在查詢的時候我修改了字段的型別為char型,因為我的實體類中是string型,所以我必須修改一下字段型別;查詢的條件是當前月以及前四個月。
然後,根據月份將兩個表右連線起來。
最後一步,我是根據兩個表中,月份大的為字段,查出了所有資料。
在寫的時候我出現了乙個問題,就是case語句還不夠熟悉,case的語法是:case when then else end;千萬記住end不能少。不然就會像我一樣報錯咯!!!
mysql 右連線 mysql 左右連線
舉例說明 假設您有兩個表,每個表只有乙個列,表資料如下 a b1 3 2 43 5 4 6注意,1,2 是a表唯一的,3,4 是公共的,並且 5,6 是b表獨有的 內連線內連線是a表的所有行交上b表的所有行得出的結果集 select from a inner join b on a.a b.b se...
MySQL左連線 右連線
表a記錄如下 aid anum 1 a20050111 2 a20050112 3 a20050113 4 a20050114 5 a20050115 表b記錄如下 bid bname 1 2006032401 2 2006032402 3 2006032403 4 2006032404 8 200...
MySQL 左連線 右連線
表a記錄如下 aid anum 1 a20050111 2 a20050112 3 a20050113 4 a20050114 5 a20050115 表b記錄如下 bid bname 1 2006032401 2 2006032402 3 2006032403 4 2006032404 8 200...