基于类似命名的列名称对sqlserver记录中的计数进行求和

时间:2015-02-05 19:34:52

标签: sql-server

在SQL服务器中,我正在尝试编写一个查询,该记录将记录汇总在另一列中具有相似名称的记录,然后仍然将记录显示给未汇总的记录。

Route  TransactionType  Count

     F43   555A          100
     F43   345A          200
     F43   543A          75
     F43   765A          125

而不是

Route  TransactionType  Count
 F43   555A-44          35
 F43   555A-42          25
 F43   555A-47          22
 F43   555A-45          18  
 F43   345A             200
 F43   543A             75
 F43   765A             125

Attemped查询示例:

Select Route, TransactionType, Sum(Count) as Sum from
(
Select Route, TransactionType,Count(TrackID) as Count, from TheTable

)A

2 个答案:

答案 0 :(得分:2)

在交易类型上添加GROUP BY。

   SELECT   
    ROUTE,
    SUBSTRING(TransactionType, 1, 4) ,
    SUM(TrackID)
FROM    TheTable
GROUP BY  ROUTE,SUBSTRING(TransactionType, 1, 4)

答案 1 :(得分:0)

如果用相似的名字表示它有' - '在那里签到,然后就可以了。 样本数据:

SELECT 'F43' AS Route, '555A-44' AS TransactionType, 35 AS Count
INTO #Temporary
UNION ALL
SELECT 'F43' AS Route, '555A-42' AS TransactionType, 25 AS Count
UNION ALL
SELECT 'F43' AS Route, '555A-47' AS TransactionType, 22 AS Count
UNION ALL
SELECT 'F43' AS Route, '555A-45' AS TransactionType, 18 AS Count
UNION ALL
SELECT 'F43' AS Route, '345A' AS TransactionType, 200 AS Count
UNION ALL
SELECT 'F43' AS Route, '543A' AS TransactionType, 75 AS Count
UNION ALL
SELECT 'F43' AS Route, '765A' AS TransactionType, 125 AS Count

实际查询。我使用CROSS APPLY只是为了使代码看起来更干净:

SELECT T.Route, F.FormattedRoute, SUM(Count) AS TotalCount
FROM #Temporary AS T
CROSS APPLY (SELECT IIF(CHARINDEX('-', T.TransactionType) = 0, T.TransactionType, LEFT(TransactionType, CHARINDEX('-', TransactionType) - 1))) AS F(FormattedRoute)
GROUP BY T.Route, F.FormattedRoute