如何在SQL Server中以以下格式获取结果?

时间:2019-04-28 22:57:08

标签: sql sql-server

我有一个名为食谱的表格,其中包含以下数据。

page_no title
-----------------
1       pancake
2       pizza
3       pasta
5       cookie

page_no 0始终为空白,而缺少的page_no则为空白,我希望输出如下所示,以获取结果中的空白页NULL值。

left_title  right_title
------------------------
NULL           pancake
Pizza          pasta
NULL           cookie

我已经尝试过此SQL语句,但未返回所需的输出:

SELECT
    CASE WHEN id % 2 = 0 
            THEN title 
    END AS left_title,
    CASE WHEN id %2 != 0 
            THEN title 
    END AS right_title
FROM
    recipes

2 个答案:

答案 0 :(得分:1)

使用CTE ..应该可以为您提供良好的CTE概述

DECLARE @table TABLE (
  pageno int,
  title varchar(30)
)

INSERT INTO @table
  VALUES (1, 'pancake')
  , (2, 'pizza')
  , (3, 'pasta')
  , (5, 'cookie')


;
WITH cte_pages
AS (  -- generate page numbers
SELECT
  0 n,
  MAX(pageno) maxpgno
FROM @table
UNION ALL
SELECT
  n + 1 n,
  maxpgno
FROM cte_pages
WHERE n <= maxpgno),
cte_left
AS (   --- even
SELECT
  n,
  ROW_NUMBER() OVER (ORDER BY n) rn
FROM cte_pages
WHERE n % 2 = 0),
cte_right
AS (   --- odd
SELECT
  n,
  ROW_NUMBER() OVER (ORDER BY n) rn
FROM cte_pages
WHERE n % 2 <> 0)
SELECT
  tl.title left_title,
  tr.title right_title    --- final output
FROM cte_left l
INNER JOIN cte_right r
  ON l.rn = r.rn
LEFT OUTER JOIN @table tl
  ON tl.pageno = l.n
LEFT OUTER JOIN @table tr
  ON tr.pageno = r.n

答案 1 :(得分:0)

您非常亲密。您只需要聚合:

select max(case when id % 2 = 0 then title end) as left_title,
       max(case when id % 2 = 1 then title end) as right_title
from recipes
group by id / 2;

SQL Server执行整数除法,因此id / 2始终是整数。