[英]T-SQL - multiple comma-separated values on a single line
I have table (T-SQL) with 2 attributes - Code and Range. 我有2个属性的表(T-SQL)-代码和范围。
Code Range
-------------------- ----------
5000_RANGE 5001..5003
5001 NULL
5002 NULL
5003 NULL
5802 NULL
5802_RANGE 5802..5804
5803 NULL
5804 NULL
6401 NULL
I'm trying to write a simple query to get the Code values with '_RANGE' postfix and the Code values (separated by commas) specified by Range attribute on a single line. 我正在尝试编写一个简单的查询,以获取带有'_RANGE'后缀的代码值和由Range属性在一行上指定的代码值(以逗号分隔)。
Code Range
-------------------- --------------
5000_RANGE 5001,5002,5003
5802_RANGE 5802,5803,5804
What is the best solution? 最好的解决方案是什么? Maybe somehow by using XML Path()? 也许以某种方式通过使用XML Path()?
You can get the list using a self-join: 您可以使用自连接获取列表:
select range.code, c.code
from (select code, range
from t
where code like '%RANGE'
) range left outer join
(select t.*
from t
where code not like '%RANGE'
) c
on c.code between left(range.range, 4) and right(range.range, 4)
Getting them into a comma separate list depends on the database. 将它们放入逗号分隔的列表取决于数据库。 Here is the method in MySQL: 这是MySQL中的方法:
select range.code, group_concat(c.code)
from (select code, range
from t
where code like '%RANGE'
) range left outer join
(select t.*
from t
where code not like '%RANGE'
) c
on c.code between left(range.range, 4) and right(range.range, 4)
group by range.code
Try this. 尝试这个。 Create a function like below: 创建如下函数:
ALTER FUNCTION GetRangeText
(
@Value VARCHAR(50)
) RETURNS VARCHAR(100)
AS
BEGIN
DECLARE @Start AS INT
DECLARE @End AS INT
DECLARE @RangeText AS VARCHAR(200)
SET @RangeText = ''
SET @Start = CAST(SUBSTRING(@Value, 0, CHARINDEX('...', @Value)) AS INT)
SET @End = CAST(SUBSTRING(@Value, CHARINDEX('...', @Value) + 3, LEN(@Value)) AS INT)
WHILE @Start <= @End
BEGIN
SET @RangeText = @RangeText + CAST(@Start AS VARCHAR(100)) + ','
SET @Start = @Start + 1
END
RETURN @RangeText
END
Consume the function in the SELECT query like below 如下所示在SELECT查询中使用该函数
SELECT Code, dbo.GetRangeText(Range) FROM Table1 WHERE Code LIKE '%_RANGE'
This will give the excepted output. 这将给出例外的输出。
You didn't specify which DBMS you are using. 您没有指定正在使用的DBMS。 If you are using MySQL you could use a query like this: 如果您使用的是MySQL,则可以使用以下查询:
SELECT
Code,
GROUP_CONCAT(SUBSTRING_INDEX(rng, '..', 1)+numbers.digit) ranges
FROM
(SELECT 0 digit UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL
SELECT 4 UNION ALL SELECT 4 UNION ALL SELECT 5) numbers
INNER JOIN
codes
ON SUBSTRING_INDEX(rng, '..', -1)-SUBSTRING_INDEX(rng, '..', 1)>=numbers.digit
WHERE
rng like '%..%'
GROUP BY
Code
Which gives exatly the result you need. 完美地给出了您需要的结果。
Please see fiddle here . 请看这里的小提琴。 It can be improved to support larger ranges. 可以进行改进以支持更大的范围。
Something like 就像是
SELECT Code, Range FROM code_table WHERE Code LIKE "%_RANGE"
Not sure about presenting the range how you like. 不确定如何介绍您喜欢的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.