SQL查询,添加包含字符串的值

时间:2017-12-20 19:39:55

标签: sql

我有这张桌子:

enter image description here

我想锻炼邦德兄弟每小时有多少巴士行程 预期结果是每小时7次

我的问题是如何添加包含字符串的值?

SELECT Operator, SUM(Frequency) AS “Total Frequency”
FROM Bus Routes

我不认为这会起作用吗?

由于

3 个答案:

答案 0 :(得分:1)

表示

declare @table as table (
    group_id int,
    content varchar(100)
)

insert into @table values (2, '2 per hour')
insert into @table values (1, '1 per hour')
insert into @table values (1, '6 per hour')
insert into @table values (1, '')
insert into @table values (3, '9 per hour')
insert into @table values (3, null)

select * from @table

DO

select t.group_id, SUM(t.content) content_sum
    from  (select group_id, convert(int, REPLACE(content, ' per hour', '')) 
content from @table) t
    group by t.group_id

答案 1 :(得分:1)

借用这个How to get the numeric part from a string using T-SQL?,你可以做这样的事情(注意转换为整数):

SELECT Operator, SUM(CAST(left(Frequency, patindex('%[^0-9]%', Frequency+'.') - 1) AS INT))
FROM 
(VALUES
('2 per hour','Ok Travel')
,('6 per hour','Diamond Buses')
,('1 per hour','Bond Brothers')
,('6 per hour','Bond Brothers')
,('','Diamond Buses')
) BusRulles(Frequency,Operator)
GROUP BY Operator

答案 2 :(得分:0)

WITH CTE AS(
SELECT  ts.Destination ,
        CONVERT(INT,REPLACE(ts.Frequency, ' per hour','')) AS Frequency ,
        ts.Operator ,
        ts.[Route Number] ,
        ts.Start
FROM dbo.temp_Sqlcheck ts
WHERE ts.Frequency IS NOT NULL OR ts.Frequency <>''
)

SELECT CTE.Operator, SUM(CTE.Frequency) AS Frequency from CTE
GROUP BY CTE.Operator 

这不会计算频率中的NULL或空值。