简体   繁体   English

我可以在Sql Server 2012中使用SQL语句展平标头和明细记录吗

[英]Can I flatten out header and detail records with a SQL Statement in Sql Server 2012

I have the following select: 我有以下选择:

SELECT TOP 1000 [ObjectiveId]
      ,[Name]
      ,[Text]
  FROM [dbo].[Objective]

It gives me 它给我

Name    Text
0100    Header1
0101    Detail1
0102    Detail2
0200    Header2
0201    Detail1a
0202    Detail1b

Is there a way I could make a string like this with a ||| 有没有办法我可以用|||这样的字符串 divider from the data. 从数据中除法。

Header1  |||  Detail1
Header1  |||  Detail2
Header2  |||  Detail1a
Header2  |||  Detail1b etc. 

The key here is that when the last two digits of name are "00" then it's a header row for following detail rows. 这里的关键是,当名称的最后两位为“ 00”时,它是用于跟随详细信息行的标题行。

; WITH headers AS (
  SELECT Name
       , Text
  FROM   dbo.Objective
  WHERE  Right(Name, 2) = '00'
)
, details AS (
  SELECT Name
       , Text
  FROM   dbo.Objective
  WHERE  Right(Name, 2) <> '00'
)
SELECT headers.Text + ' ||| ' + details.Text
FROM   headers
 LEFT
  JOIN details
    ON Left(details.name, 2) = Left(headers.name, 2)

Query: 查询:

SQLFIDDLEExample SQLFIDDLEExample

SELECT t1.Text + ' ||| ' + t2.Text AS clm
FROM Objective t1
  LEFT JOIN Objective t2
    ON SUBSTRING(t2.Name, 1, 2) = SUBSTRING(t1.Name, 1, 2)
    AND t2.Name not like '%00'
WHERE t1.Name like '%00'

Result: 结果:

|                  CLM |
------------------------
|  Header1 ||| Detail1 |
|  Header1 ||| Detail2 |
| Header2 ||| Detail1a |
| Header2 ||| Detail1b |

Try this: 尝试这个:

;WITH Header
AS
(
    SELECT  LEFT([Name], 2) AS HeaderKey,
            [Name], 
            [Text]
    FROM Objective
    WHERE RIGHT([Name], 2) = '00'
),
Detail
As
(
    SELECT  LEFT([Name], 2) AS HeaderKey,
            [Name], 
            [Text]
    FROM Objective
    WHERE RIGHT([Name], 2) <> '00'
)
SELECT Header.[Text] + '|||' + Detail.[Text]
FROM Header
INNER JOIN Detail
    ON Header.HeaderKey = Detail.HeaderKey
select top 1000 A.[Text]+' ||| '+B.[Text]
FROM [dbo].[DILL] as A
Inner join [dbo].[DILL] as B
on substring(A.[Name],3,5) = '00'
and A.[Text] != B.[Text] 
and substring(B.[Name],1,3) = substring(A.[Name],1,3)

EDIT: Forgot to add the last line of code and use the correct JOIN 编辑:忘记添加代码的最后一行,并使用正确的JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM