顯示具有 SQL 標籤的文章。 顯示所有文章
顯示具有 SQL 標籤的文章。 顯示所有文章

2020年6月7日 星期日

UNION和UNION ALL的差別,UNION會移除重複資料

UNION會移除重複資料
UNION ALL會保留重複資料


執行計畫:
UNION會先Concatenation 再Distinct Sort再輸出結果
UNION ALL只有Concatenation就輸出結果

GROUP BY會去掉重複的資料


2016年4月17日 星期日

2016年4月16日 星期六

各種資料庫Select first rows的方式

SQL - Select first 10 rows only? - Stack Overflow
http://stackoverflow.com/questions/1891789/sql-select-first-10-rows-only

(小工具)依照TABLE清單產生SQL語法

因為最近有要將DB2資料庫所有的Table匯出成del檔
自己用C#寫了一個小工具去產生export語法
如有需要可以自行下載

專案網址:
https://bitbucket.org/rexhuang/c-_sqlstringconcatenate
執行檔位於\SQLStringConcatenate\bin\Release資料夾下

程式介面:

各種資料庫List All Tables

How to List All Tables and Describe Tables in Oracle, MySQL, DB2 and PostgreSQL
http://onewebsql.com/blog/list-all-tables

2016年4月10日 星期日

使用PIVOT函數建立各月份銷售統計報表




2014-08故意沒把NULL改成0
2014-09使用ISNULL函數,其他月份使用COALESCE函數
COALESCE函數是ANSI SQL-92標準,ISNULL函數不是標準
另外SQL Server 2005之後才支援PIVOT函數
Oracle 11g之後也支援函數
MySQL沒有PIVOT函數,要使用GROUP_CONCAT

ref:
比較 ISNULL() 函數以及 COALESCE() 函數
SQL server : Replacing NULL with 0 in a query - Stack Overflow
Databases that support PIVOT/UNPIVOT syntax:

下載Adventure Works 2014 Sample Databases:
https://msftdbprodsamples.codeplex.com/releases/view/125550

2015年10月23日 星期五

Select count(*) from multiple tables

http://stackoverflow.com/questions/606234/select-count-from-multiple-tables

 
橫的
with t1_count as (select count(*) c1 from t1),
     t2_count as (select count(*) c2 from t2)
select c1,
       c2
from   t1_count,
       t2_count
/

select c1,
       c2
from   (select count(*) c1 from t1) t1_count,
       (select count(*) c2 from t2) t2_count
/


直的
SELECT 'TAB1' AS TABLE_NAME, COUNT(*) FROM TAB1
 UNION ALL SELECT 'TAB2' AS TABLE_NAME, COUNT(*) FROM TAB2
 UNION ALL SELECT 'TAB3' AS TABLE_NAME, COUNT(*) FROM TAB3
 UNION ALL SELECT 'TAB4' AS TABLE_NAME, COUNT(*) FROM TAB4