这是我得到的当前SQL
SELECT STUFF((SELECT ', ' + RTRIM(CAST(ShipmentCargoContainersSummary.units AS VARCHAR(20))) + ' X ' +
CAST(RTRIM(ContainerType.description) AS VARCHAR(20)) [text()] FROM ...
FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'),1,2,' ') fclVolume
FROM Shipment INNER JOIN ....
输出
我的问题是如何修复此代码,以便我可以将所有这些计为11行并得到这样的预期输出:8 X 40Hc, 3 X 20GP
。
答案 0 :(得分:0)
假设您有以下数据:
2X40'HC
1X40'HC
1X40'HC
1X20'GP
1X40'HC
1X40'HC
1X40'HC
1X20'GP
1X40'HC
1X40'HC
1X20'GP
您的最终结果:
8 X 40Hc, 3 X 20GP
如果一切正确,那么您可以在SQL Command
下面尝试:
;WITH CTE
AS (
SELECT COUNT(CONVERT(INT, SUBSTRING(DATA, 3, 2))) DATA1,
SUBSTRING(DATA, 3, LEN(DATA)) DATA
FROM <tablename>
GROUP BY SUBSTRING(DATA, 3, LEN(DATA)))
SELECT [DATA] = STUFF(
(
SELECT ','+REPLACE(CONVERT(NVARCHAR(MAX), DATA1)+'X'+DATA, '''', '')
FROM CTE FOR XML PATH('')
), 1, 1, '');
结果:
3X20GP,8X40HC
希望,上面的SQL命令可以帮到你。
答案 1 :(得分:0)
您可以使用此查询(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