【发布时间】:2015-08-25 18:48:30
【问题描述】:
我正在为一些 SQL 代码苦苦挣扎几个小时。我正在尝试将 2 个不同的值组合在一行中,但如果一个值不存在(所以没有结果),则根本不会出现行。
更清楚一点:我有一个包含 2 个不同值的位置,它们来自两个查询。这工作正常,但有时第二个查询没有结果(可能发生,还不错),但也没有显示第一个值。
Declare @Start datetime,
@Ende datetime;
SET @Start = '01.04.2015';
SET @Ende = '30.04.2015';
SELECT t1.[Location Code], CAST(t1.Umsatz as DECIMAL(18,2))as Umsatz , CAST(t2.Ersatznachweis as DECIMAL(18,2)) as Ersatznachweis
FROM (
SELECT [Location Code], SUM(WareBrutto) AS Umsatz
FROM (SELECT DISTINCT [Location Code], [Document No_] , WareBrutto from [Item Ledger Entry]
WHERE [Location Code] > '0000' and [Location Code] < '0040' and [Document Date] >= @Start and [Document Date] <= @Ende) t
GROUP BY [Location Code]) as t1,
(select [Location Code], sum([Quantity]*Bruttopreis) as Ersatznachweis from [Item Ledger Entry]
where [Location Code] > '0000' and [Location Code] < '0040' and [Item No_] not IN ('00009000','00009900','00009906') and Gutschrift = '1' and [Document Date] >= @Start and [Document Date] <= @Ende
Group By [Location Code]) as t2
where t1.[Location Code] = t2.[Location Code]
order by t1.[Location Code]
这是有时不返回值的第二个查询。
(select [Location Code], sum([Quantity]*Bruttopreis) as Ersatznachweis from [Item Ledger Entry]
where [Location Code] > '0000' and [Location Code] < '0040' and [Item No_] not IN ('00009000','00009900','00009906') and Gutschrift = '1' and [Document Date] >= @Start and [Document Date] <= @Ende
Group By [Location Code]) as t2
但是到最后没有t2的结果。[Location code] t1的结果也没有显示出来。
where t1.[Location Code] = t2.[Location Code]
我希望 t2 在没有结果时获得零值。我尝试了 isnull 和 coalesec 选项,但我无法获得不错的结果。它不在那里,或者我收到错误消息。
在此感谢...
在 2012 MSSQL 服务器上使用 Toad for SQl。
【问题讨论】:
-
从
from子句中删除逗号并使用明确的JOIN语法。这样您就可以轻松地发现并解决问题。
标签: sql sql-server record