您可以使用此查詢(WITH部分只是用數據模擬原始表)。
在內部查詢中刪除所有空格並找到X的位置。
在下一個查詢(從內部開始)中,似乎提取了qty以及字符串的其餘部分(不包括X)。
在下一個查詢GROUP BY被做出(我把兩個假設,一個與SUM和一個與COUNT,但你可以消除一個對你沒有意思)。
外部查詢格式輸出,因爲它看起來你需要。
WITH X AS (SELECT '2 X 40''HC' AS VOLUME
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '12 X 20''GP'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 20''GP'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 40''HC'
UNION ALL SELECT '1 X 20''GP')
SELECT CAST (SUM_QTY AS VARCHAR(5))+' X ' +GRP AS ONE_CASE
,CAST (NUM_QTY AS VARCHAR(5))+' X ' +GRP AS SECOND_CASE
FROM (SELECT GRP, SUM(QTY) AS SUM_QTY, COUNT(*) AS NUM_QTY
FROM (
SELECT CAST(LEFT(VOLUME,pos1-1) AS int) AS QTY,
SUBSTRING(VOLUME,pos1+1,LEN(VOLUME)) AS GRP
FROM (SELECT CHARINDEX('X',REPLACE(VOLUME,' ' , '')) pos1, REPLACE(VOLUME,' ' , '') AS VOLUME FROM X) A
) B
GROUP BY GRP
) C
輸出:
ONE_CASE SECOND_CASE
14 X 20'GP 3 X 20'GP
9 X 40'HC 8 X 40'HC
@YogeshSharma感謝,並進行編輯後:) –
@IntanNurShafienaz添加樣本數據(它是如何存儲在數據庫表) –
這是沒有更優雅的解決將單元連接到描述的中間步驟。你的數據如何實際存儲在數據庫中? – iamdave