按子串和总和分组

时间:2015-07-22 05:28:00

标签: sql sql-server

这是我的查询

select U_YBID, T1.onhand
from oitw T1
inner join oitm T2 on T1.ItemCode=T2.ItemCode
where T1.WhsCode='01' and U_YBID is not null and u_YBId like '%/%'

它提供如下输出:

302/02  41.000000
302/01  23.000000
X82/02  20.000000
355/01  2.000000
355/02  4.000000
355/03  5.000000

我需要查询,其中包含sum和id,例如:

302    64
x82    20
355    11 

4 个答案:

答案 0 :(得分:2)

您可以使用left

select left(U_YBID, 3)
     , sum(T1.onhand)
from oitw T1
inner join oitm T2 on T1.ItemCode = T2.ItemCode
where T1.WhsCode = '01' and u_YBId like '%/%
group by left(U_YBID, 3)

答案 1 :(得分:0)

您必须使用substringgroup by

select substring(U_YBID,1,3), sum(T1.onhand)
from oitw T1
inner join oitm T2 on T1.ItemCode=T2.ItemCode
where T1.WhsCode='01' and U_YBID is not null and u_YBId like '%/%
group by substring(U_YBID,1,3)

答案 2 :(得分:0)

尝试使用mid功能 https://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_mid

SELECT MID(U_YBID,1,3), 
       SUM(T1.onhand)
       FROM oitw T1
       INNER JOIN oitm T2 on T1.ItemCode=T2.ItemCode
       WHERE T1.WhsCode='01' and U_YBID is not null and u_YBId like '%/%
       GROUP MID(U_YBID,1,3);

答案 3 :(得分:0)

如果U_YBID之前的/列中的字符串长度不是3的静态,那么您可以将查询编写为:

SELECT U_YBID,SUM (T1.onhand) AS T1.onhand
FROM 
( 
select PARSENAME(REPLACE(U_YBID, '/', '.'), 2) AS U_YBID , T1.onhand
from oitw T1
inner join oitm T2 on T1.ItemCode=T2.ItemCode
where T1.WhsCode='01' and U_YBID is not null and u_YBId like '%/%'
)AS T
GROUP BY U_YBID

您可以详细了解PARSENAME函数here..