我有一个表和一列包含id号码+数字+字母。我知道如何分离并创建另一个(新)列,但我想按新列分组:
SELECT A.COLUMN1 ,
B.COLUMN1,
(LEFT(SUBSTRING(B.COLUMN1, PATINDEX('%[0-9.-]%', B.COLUMN1), 10),
PATINDEX('%[^0-9.-]%', SUBSTRING(B.COLUMN1, PATINDEX('%[0-9.-]%', B.COLUMN1), 10) + 'X') -1)) as name2
FROM TABLE_B AS B
LEFT OUTER JOIN TABLE_A AS A ON B.COLUMN123 = A.COLUMN123
WHERE A.COLUMN1='VALUE'
GROUP BY B.COLUMN1, A.COLUMN1
所以我的报告如下:
name1 name2 name2
VALUE1 1 1
VALUE 2 2
VALUE3 3 1
VALUE 4 4
VALUE 27xz 27
VALUE 27zx 27
如何按名称2分组?
答案 0 :(得分:5)
最简单的方法是使用CTE或子查询:
WITH cte as (
SELECT A.COLUMN1, B.COLUMN1,
(LEFT(SUBSTRING(B.COLUMN1, PATINDEX('%[0-9.-]%', B.COLUMN1), 10),
PATINDEX('%[^0-9.-]%', SUBSTRING(B.COLUMN1, PATINDEX('%[0-9.-]%', B.COLUMN1), 10) + 'X') -1)) as new_column
FROM TABLE_B B LEFT OUTER JOIN
TABLE_A A
ON B.COLUMN123 = A.COLUMN123
WHERE A.COLUMN1 = 'VALUE'
)
SELECT new_column, COUNT(*)
FROM cte
GROUP BY new_column;