SQL查询从输入参数的单个字段中查找多个值

时间:2015-10-02 19:24:51

标签: mysql sql sql-server

是否可以从单个字段中找到多个值,这些值在一组输入参数中?

数据库示例将是这样的

<tr ng-repeat="result in results">

我需要一些东西给我这个输出

User             Login_DT_TM
0001             1/1/2015 12:00, 1/1/2015 12:30,1/6/2015 09:00
0002             1/3/2015 13:00, 1/5/2015 16:00

login_DT_TM =&gt; 2015年1月1日'00:00'和login_DT_TM =&lt; 2015年1月4日'23:59'

2 个答案:

答案 0 :(得分:0)

SQL Fiddle

MS SQL Server 2008架构设置

CREATE TABLE Test_Table ([User] VARCHAR(10) , Login_DT_TM VARCHAR(4000))
INSERT INTO Test_Table VALUES
('0001','1/1/2015 12:00, 1/1/2015 12:30,1/6/2015 09:00'),
('0002','1/3/2015 13:00, 1/5/2015 16:00')

查询1

WITH X AS
(
 SELECT [User] 
       ,CAST(Split.a.value('.', 'VARCHAR(100)')  AS DATETIME) Login_DT_TM
 FROM   
     (SELECT    [User]
              ,Cast ('<X>' + Replace(Login_DT_TM, ',', '</X><X>') + '</X>' AS XML) AS Data
       FROM    Test_Table
     ) AS t 
     CROSS APPLY Data.nodes ('/X') AS Split(a) 
)
SELECT  [User]
       ,Login_DT_TM
FROM X
WHERE Login_DT_TM > '20141231'
 AND  Login_DT_TM < '20150105'

<强> Results

| User |        Login_DT_TM        |
|------|---------------------------|
| 0001 | 2015-01-01 12:00:00.000   |
| 0001 | 2015-01-01 12:30:00.000   |
| 0002 | 2015-01-03 13:00:00.000   |

答案 1 :(得分:0)

这应符合您的期望:

DECLARE @table TABLE
    (
      [USER] NVARCHAR(30) ,
      LOGIN NVARCHAR(300)
    );

INSERT  INTO @table
        ( [USER], LOGIN )
VALUES  ( N'0001', 
          N'1/1/2015 12:00, 1/1/2015 12:30, 1/6/2015 09:00'
          ),
        ( N'0002',
          N'1/3/2015 13:00, 1/5/2015 16:00'
          );


WITH    tmp ( userid, part , rest  )
          AS ( SELECT   [USER] ,
                        CONVERT(NVARCHAR(300),LEFT(LOGIN, CHARINDEX(',', LOGIN + ',') - 1)) ,
                        CONVERT(NVARCHAR(300),STUFF(LOGIN, 1, CHARINDEX(',', LOGIN + ',')+1, ''))
               FROM     @table
               UNION ALL
               SELECT   userid ,
                        CONVERT(NVARCHAR(300),LEFT(rest, CHARINDEX(',', rest + ',') - 1)) ,
                        CONVERT(NVARCHAR(300),STUFF(rest, 1, CHARINDEX(',', rest + ',')+1, '') )
               FROM     tmp
               WHERE    rest > ''
             )
    SELECT  tmp.userid, tmp.part
    FROM    tmp;