当标准找不到行时,选择0

时间:2017-12-20 12:00:08

标签: sql-server tsql

我无法弄清楚如何包含查询找不到的行。查询看起来像:

select 'EXPORT',count(z.zamodbpoz_id),k.nazwa,sum(z.ilosc) from klaswytw k
inner join wytwor w on w.klaswytw_id = k.klaswytw_id
inner join zamodbpoz z on w.wytwor_id = z.wytwor_id
inner join zamodb za on za.zamodb_id = z.zamodb_id
where 
k.klaswytw_id in (
84,88,89,92,93,119,133,134,199,235,237,286,287
,289,290,291,434,440,108,288,481,138,137,206,207
,212,91,136,135,220,218,85,407,411,115,410,87,500
,86,435,219,106,405,436,116,243,441,442,443,29,425
,32,426,23,31,96,124,422,22,38,39,40,428,486,132,430
,36,432,496,482,487,141,140,226,131,69,190,478,477,18,431)
 and 
 za.typzamodb_id in (13,12,19,21) and month(za.datdok) = 5 and year(za.datdok) = 2017
GROUP by k.nazwa
order by k.nazwa

EXPORT | 12 | LT11A1_XYZ | 33.000 EXPORT | 2 | LT1300_ABC | 45.000

它返回43行(例如上面的代码),这意味着从范围中找到了43 k.klaswytw_id。如何更改此查询以包括未创建k.klaswytw_id?当然它会返回NULL0值,但我可以做到。

2 个答案:

答案 0 :(得分:1)

尝试以下

select 'EXPORT',count(z.zamodbpoz_id),k.nazwa,sum(z.ilosc)
from
  (
    select *
    from klaswytw
    where klaswytw_id in (
                84,88,89,92,93,119,133,134,199,235,237,286,287
                ,289,290,291,434,440,108,288,481,138,137,206,207
                ,212,91,136,135,220,218,85,407,411,115,410,87,500
                ,86,435,219,106,405,436,116,243,441,442,443,29,425
                ,32,426,23,31,96,124,422,22,38,39,40,428,486,132,430
                ,36,432,496,482,487,141,140,226,131,69,190,478,477,18,431)
  ) k
left join wytwor w on w.klaswytw_id = k.klaswytw_id
left join zamodbpoz z on w.wytwor_id = z.wytwor_id
left join zamodb za on za.zamodb_id = z.zamodb_id and za.typzamodb_id in (13,12,19,21) and month(za.datdok) = 5 and year(za.datdok) = 2017
GROUP by k.nazwa
order by k.nazwa

答案 1 :(得分:0)

您可能希望将where语句更改为在()语句中的k.klasytw_id之后具有OR,以便它返回具有正确k.klaswytw_id或具有正确日期/ typzamodb_id的结果的结果。

 where 
 k.klaswytw_id in (
 84,88,89,92,93,119,133,134,199,235,237,286,287
 ,289,290,291,434,440,108,288,481,138,137,206,207
 ,212,91,136,135,220,218,85,407,411,115,410,87,500
 ,86,435,219,106,405,436,116,243,441,442,443,29,425
 ,32,426,23,31,96,124,422,22,38,39,40,428,486,132,430
 ,36,432,496,482,487,141,140,226,131,69,190,478,477,18,431)
  OR
  za.typzamodb_id in (13,12,19,21) and month(za.datdok) = 5 and 
 year(za.datdok) = 2017

或者,如果您希望包含k.klaswytw_id与w.klaswytw_id不匹配的结果,您将需要查看左/右/外连接。

https://www.w3schools.com/sql/sql_join.asp