如果为null,则向上移动列单元格

时间:2012-06-27 19:01:14

标签: sql sql-server sql-server-2008 tsql

我正在尝试将结果集格式化为sql语句以放入水晶报表的命令中。如果行单元格为空,我需要它向上移动。我知道这不是sql的用途,但它是客户端规范。我在这里有一个例子,http://sqlfiddle.com/#!3/76999/11

这就是我现在所拥有的

1 http://img259.imageshack.us/img259/7186/have.jpg

这就是我需要的

1 http://img59.imageshack.us/img59/465/needd.jpg

提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个并告诉我它是如何运作的:

WITH DATA1 (ID, TaxCode)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY TaxCode desc) AS ID, A.TaxCode FROM Table A)

, DATA2 (ID, OwnerTax)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY Ownertax desc) AS ID, A.OwnerTax FROM Table A)

, DATA3 (ID, OwnerOther)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY OwnerOther desc) AS ID, A.OwnerOther FROM Table A)

, DATA4 (ID, DEDCode)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY DEDCode desc) AS ID, A.DEDCode FROM Table A)

SELECT DATA1.TaxCode, DATA2.OwnerTax, DATA3.OwnerOther, DATA4.DEDCode
FROM DATA1 
LEFT JOIN DATA2 ON DATA1.ID = DATA2.ID
LEFT JOIN Data3 ON DATA1.ID = DATA3.ID
LEFT JOIN Data4 ON DATA1.ID = DATA4.ID

如果您将其直接复制并粘贴到右侧窗口,则以下SQL将在链接http://sqlfiddle.com/#!3/76999/11上运行:

With Source1 (TaxCode, OwnerTax, OwnerOther, dedCode)
As(
SELECT 
CASE WHEN [Adjdesc] = 'TAX' THEN [TaxCode] ELSE null END AS TaxCode,
CASE WHEN [Adjdesc] = 'TAX' THEN [adj] END AS OwnerTax, 
CASE WHEN [Adjdesc] <> 'TAX' THEN [adj] END AS OwnerOther,
CASE WHEN [Adjdesc] <> 'TAX' THEN [TaxCode] ELSE null END AS dedCode

FROM test4 AS A
WHERE adj IS NOT NULL)

, DATA1 (ID, TaxCode)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY TaxCode desc) AS ID, A.TaxCode FROM Source1 A)

, DATA2 (ID, OwnerTax)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY Ownertax desc) AS ID, A.OwnerTax FROM Source1 A)

, DATA3 (ID, OwnerOther)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY OwnerOther desc) AS ID, A.OwnerOther FROM Source1 A)

, DATA4 (ID, DEDCode)
AS
(SELECT ROW_NUMBER() OVER (ORDER BY DEDCode desc) AS ID, A.DEDCode FROM Source1 A)

SELECT DATA1.TaxCode, DATA2.OwnerTax, DATA3.OwnerOther, DATA4.DEDCode
FROM DATA1 
LEFT JOIN DATA2 ON DATA1.ID = DATA2.ID
LEFT JOIN Data3 ON DATA1.ID = DATA3.ID
LEFT JOIN Data4 ON DATA1.ID = DATA4.ID