2014-07-23 62 views

回答

1

對於SQL Server和MySQL

SELECT LEFT(colName,1) as Alphabet,COUNT(*) as CountNumber 
FROM tableName 
GROUP BY LEFT(colName,1) 

如果你想指望所有26個字母列表中,首先你必須拿一張臨時表並用所有26個字母填充它,然後用上面的結果集做一個LEFT JOIN。

CREATE TABLE #AlphabetTable(Alphabet CHAR(1)); 

INSERT INTO #AlphabetTable VALUES('A'); 
INSERT INTO #AlphabetTable VALUES('B'); 
. 
. 
. 
INSERT INTO #AlphabetTable VALUES('Z'); 

然後在下面的查詢中顯示計數爲零,如果對於特定字母表不存在列值。

SELECT a.Alphabet,COALESCE(CountNumber,0) 
FROM #AlphabetTable a 
LEFT JOIN 
      (
      SELECT LEFT(colName,1) as Alphabet,COUNT(*) as CountNumber 
      FROM tableName 
      GROUP BY LEFT(colName,1) 

     ) t 
    ON a.Alphabet=t.Alphabet 
0

對於CLI_ID一個表CLIENT作​​爲唯一標識符列和CLI_NAME作爲列

選擇LEFT(CLI_NAME,1)FirstLetter,通過LEFT從CLIENT 組計數(CLI_ID)CNT(CLI_NAME,1) order by Cnt desc