需要帮助构建SQL

时间:2017-02-15 09:13:56

标签: sql sql-server

我有这样的查询,

SELECT DISTINCT X,Y,Z from ABC;

假设它产生的结果如

         X              |    Y   |   Z
------------------------|--------|------
a/b/c/34y3bkfoi         | Data1  | Data2
a/b/c/56egdhdhh         | Data1  | Data2
a/b/c/h5747858i         | Data1  | Data2
a/b/c/657sgsr65         | Data1  | Data2
x/y/z/67dhgg45h         | Data1  | Data2
x/y/z/6hd467ydh         | Data1  | Data2

现在我想将第一列的数据分组到'a / b / c'。我不关心其他事情。

或者简单地说我想要DISTINCT必须应用于特定的上下文'%/%/%/'。

预期结果:

      X     |    Y   |   Z
------------|--------|------
a/b/c/      | Data1  | Data2
x/y/z/      | Data1  | Data2

任何建议?。

5 个答案:

答案 0 :(得分:1)

这是你需要的吗?

 SELECT DISTINCT X,Y,Z from ABC WHERE X LIKE 'a/b/c/%'

答案 1 :(得分:1)

你可以像这样使用带有instr的substr:

select substr(X, 1, Instr(X, '/', -1) - 1) as X1,  substr(X, Instr(X, '/', -1) + 1) as X2, Y, Z 
from
(select 'a/b/c/35235235' as X, 'Data1' as Y, 'Data2' as Z from dual);

输出是:

 X1    | X2       |  Y  |  Z
------------------------------
'a/b/c'|'35235235'|Data1|Data2

然后你group by X1

答案 2 :(得分:0)

使用<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <button id="search"> <span class="glyphicon glyphicon-picture"></span> <span id="output">Upload Image</span> <span class="glyphicon glyphicon-search">Browse</span> <input id="hideFile" type="file" multiple/> </button>DISTINCT

LEFT

答案 3 :(得分:0)

试试这个:

SELECT X, Y, Z, t.i,
       LEFT(X, LEN(X) - t.i + 1),
       RIGHT(X, t.i - 1)
FROM ABC
CROSS APPLY (SELECT CHARINDEX('/', REVERSE(X))) AS t(i)

要选择不同,您可以使用ROW_NUMBER

;WITH CTE AS (
    SELECT X, Y, Z, t.i,
           LEFT(X, LEN(X) - t.i + 1) AS l,
           RIGHT(X, t.i - 1) AS r,
           ROW_NUMBER() OVER (PARTITION BY LEFT(X, LEN(X) - t.i + 1) 
                              ORDER BY X) AS rn
    FROM ABC
    CROSS APPLY (SELECT CHARINDEX('/', REVERSE(X))) AS t(i)
)
SELECT 
FROM CTE
WHERE rn = 1

答案 4 :(得分:0)

谢谢你们。 我使用

得到了预期的输出
SELECT DISTINCT(SUBSTR(X,1,INSTR(X,'/',1,3))),Y,Z from ABC;