首先,我是SQL的初学者。
我在表格中有一个名为State
的列,其中包含如下所示的数据
State
Karnataka
Uttar Pradesh
Tamilnadu
Telangana
Kerela
Andhra Pradesh
我想知道每个州有多少个元音,每个元音的结果应该是分开的。
预期产出:
State Count of a Count of e Count of i Count of o Count of u
Karnataka 4 0 0 0 0
Uttar Pradesh 2 1 0 0 1
答案 0 :(得分:4)
请尝试以下SQL:
SELECT
State,
LEN(state)-LEN(REPLACE(state,'a','')) 'Count of a',
LEN(state)-LEN(REPLACE(state,'e','')) 'Count of e',
LEN(state)-LEN(REPLACE(state,'i','')) 'Count of i',
LEN(state)-LEN(REPLACE(state,'o','')) 'Count of o',
LEN(state)-LEN(REPLACE(state,'u','')) 'Count of u'
FROM TableName
答案 1 :(得分:1)
使用PIVOT:
CREATE TABLE #TEST ([STATE] NVARCHAR(MAX))
INSERT INTO #TEST VALUES ('Karnataka' )
INSERT INTO #TEST VALUES ('Uttar Pradesh' )
INSERT INTO #TEST VALUES ('Tamilnadu' )
INSERT INTO #TEST VALUES ('Telangana' )
INSERT INTO #TEST VALUES ('Kerela' )
INSERT INTO #TEST VALUES ('Andhra Pradesh')
SELECT *
FROM
(
SELECT [STATE], N, LEN([STATE]) - LEN(REPLACE([STATE], N,'')) AS VOWELCOUNT
FROM #TEST
CROSS JOIN (VALUES('A'),('E'),('I'),('O'),('U')) AS A(N)
) PVT
PIVOT (MAX(VOWELCOUNT) FOR N IN ([A],[E],[I],[O],[U])) AS D