目前分類:SQL (6)

瀏覽方式: 標題列表 簡短摘要

希望針對資料不同的欄位總合做比較,使用pivot來轉換

先處理原始資料,只要取deal_id和指定type的資料

select deal_id, type from History where deal_id is not null and type in (20,30)

撈出結果為

SQL1.JPG

然後希望是相同deal_id的資料可以排成一排
EX: TITLE= DEAL_ID、TYPE20、TYPE30 

select * from(
select deal_id, type from History where deal_id is not null and type in (20,30)
) -- pivot要直接接結果
pivot(
   count(type)
   for type in (20 as TWSUM,30 as THSUM) -- 翻轉欄位為type ,另外將數字結果定別名
)

SQL1.JPG

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

將多row的相同資料串成string

EX: 相同的DISNO有不同的CITYID,希望把他串成一個string

擷取.JPG

擷取.JPG

方法1: 使用LISTAGG  (ORACLE 11g, 有長度限制4000char)
SELECT DISNO, LISTAGG(CITYID, ',') WITHIN GROUP(ORDER BY DISNO) CITYIDS
FROM ADDR WHERE DISNO= '40230'
GROUP BY DISNO; 

方法2:  使用XMLAGG

SELECT DISNO, RTRIM(XMLAGG (XMLELEMENT (e, CITYID, ',')).EXTRACT ('//text()').getclobval(), ',') CITYIDS
FROM ADDR WHERE DISNO= '40230'
GROUP BY DISNO;
--CITYID資料PARSE成XML<e></e>模式,再進行串接

 


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

上個月最後一天

select add_months(trunc(last_day(sysdate)) ,-1) from dual

 

上個月第一天

select add_months(trunc(sysdate, 'mm') ,-1) from dual


文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

select orderId, count(case paid when 'N' then 1 end) from orderitem

 

use case to filter data

 

refer: https://stackoverflow.com/questions/1400078/is-it-possible-to-specify-condition-in-count


咪卡恰比 發表在 痞客邦 留言(0) 人氣()

SQL(ORACLE用) - 取得EMAIL異常資料

其他判斷就再自己加,這邊是這次有想到的一些條件

--如果有英文@,._-符號以外的資料, 搜尋出來
select id
from (
select id, nvl(length(regexp_replace(contactor_email,'[a-zA-Z0-9@,._\-]','')),0) as emailLen
from t_member
)
where emailLen>0

--如果是null, 搜尋出來
select id
from t_member
where (contactor_email is null or length(TRIM(contactor_email))=0)

--如果不含@, 搜尋出來
select id 
from t_member
where contactor_email not like '%@%'

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()

從其他DB取得資料並更新到目的TABLE

update tableA  --target table
set(
tid,
tname
)=
(
select TB.prodId, TB.ProdName  --source data
from tableB TB
where TB.id = 123456
)
where tag = 'tag123'  --target table condition

文章標籤

咪卡恰比 發表在 痞客邦 留言(0) 人氣()