1

假设我们在 SQL 表的 2 列中有这样的值

HM        BOX_NO

A          1
A          2
B          2
B          3
C          3

我想像下面这样输出这些表值我该怎么做?

A
1
2
B
2
3
C
3
4

4 回答 4

2

我假设您希望 HM 中的不同值与 BOX_NO 中的值出现在 HM 的每个值下方。

你可以这样做。可能比您预期的要复杂:

select val
from ((select distinct hm as val, 1 as ishm,
              dense_rank() over (order by HM) as ranking
       from t
      ) union all
      (select cast(box_no as varchar(255)), 0 as ishm,
              dense_rank() over (order by HM) as ranking
       from t
      )
     ) a
order by ranking, ishm desc, val
于 2012-08-22T15:30:54.397 回答
2
CREATE TABLE #t
    ([HM] varchar(1), [BOX_NO] int);

INSERT INTO #t
    ([HM], [BOX_NO])
VALUES
    ('A', 1),
    ('A', 2),
    ('B', 2),
    ('B', 3),
    ('C', 3);

SELECT  item
FROM (
    SELECT  DISTINCT HM as item, HM as display_order
    FROM    #t  
    UNION ALL
    SELECT  CAST([BOX_NO] AS VARCHAR(10)), HM + CAST([BOX_NO] AS VARCHAR(10))as display_order
    FROM    #t  
) a
ORDER BY display_order  
于 2012-08-22T15:35:38.657 回答
2
SELECT
  Value = COALESCE(CAST(BOX_NO AS varchar(10)), HM)
FROM (
  SELECT          HM, BOX_NO FROM atable
  UNION ALL
  SELECT DISTINCT HM, NULL   FROM atable
) s
ORDER BY HM, BOX_NO
;

这是SQL Fiddle的演示。

于 2012-08-23T16:42:27.630 回答
1

试试这个

Declare @t Table([HM] varchar(1), [BOX_NO] int);

INSERT INTO @t([HM], [BOX_NO])
VALUES
    ('A', 1),
    ('A', 2),
    ('B', 2),
    ('B', 3),
    ('C', 3);

;With Cte As(
Select 
      Rn
     ,HM
    ,BOX_NO
    ,HM_Grouping = HM + Cast(Rn As Varchar(1))
From (Select Rn = Row_Number() Over(Partition By HM Order by HM),*
      From @t)x)
Select HM 
From
    (Select HM,Position = HM
    From Cte Where Rn = 1
    Union All
    Select Cast(BOX_NO As Varchar(1)),HM_Grouping
    From Cte)x
Order by Position 

结果

HM
A
1
2
B
2
3
C
3
于 2012-08-22T17:03:40.973 回答