Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在另一个表中找到项时要添加到结果列表的SQL查询_Sql_Sql Server - Fatal编程技术网

在另一个表中找到项时要添加到结果列表的SQL查询

在另一个表中找到项时要添加到结果列表的SQL查询,sql,sql-server,Sql,Sql Server,我的数据库中有四个表。我有一个sql语句,它为主表提供了正确的结果,因为我需要对返回的列进行计数和求和。 然而,其中一个列(ZiNr)也在其他三个表中。我想知道ZiNr是否在另一个表中,它在结果集中返回一个值 以下是我到目前为止的sql声明: SELECT max([Product hoofdgrp]) as prdType ,max([ZiNr]) as ZiNr ,max([Eenheid]) as PackSize ,max([Omschrijving]) as ProdName ,max

我的数据库中有四个表。我有一个sql语句,它为主表提供了正确的结果,因为我需要对返回的列进行计数和求和。 然而,其中一个列(ZiNr)也在其他三个表中。我想知道ZiNr是否在另一个表中,它在结果集中返回一个值

以下是我到目前为止的sql声明:

SELECT
max([Product hoofdgrp]) as prdType
,max([ZiNr]) as ZiNr
,max([Eenheid]) as PackSize
,max([Omschrijving]) as ProdName
,max([AIP ]) as AIP
,sum([Afname aantal]) as Afname_aantal
,sum([AIP x afname aantal]) as Totaal
,max([Periode]) as Periode
FROM [reports].[dbo].[myreports]
where [Product hoofdgrp] like 'Generiek'-- AND ZiNr = '15985369'
group by ZiNr
order by Totaal desc
我需要找出ZiNr是否在另一个名为CZ的表中,并在该行中附加一个名为CZ的值

希望我问得够清楚


提前感谢

您应该能够将加入到另一个表中。确保使用
左侧外部联接
,因为
内部联接
仅包括找到匹配项的行。然后,您只需检查该表中的一列,查看是否找到匹配项(它必须是一列,否则不能为
NULL

SELECT
    MAX([Product hoofdgrp]) AS prdType,
    MAX([ZiNr]) AS ZiNr,
    MAX([Eenheid]) AS PackSize,
    MAX([Omschrijving]) AS ProdName,
    MAX([AIP ]) AS AIP,
    SUM([Afname aantal]) AS Afname_aantal,
    SUM([AIP x afname aantal]) AS Totaal,
    MAX([Periode]) AS Periode,
    CASE WHEN CZ.ZiNr IS NOT NULL THEN 'CZ' ELSE '' END AS InCZ
FROM
    [reports].dbo.MyReports R
LEFT OUTER JOIN CZ ON CZ.ZiNr = R.ZiNr
WHERE
    R.[Product hoofdgrp] LIKE 'Generiek'-- AND ZiNr = '15985369'
GROUP BY
    R.ZiNr,
    CZ.ZiNr
ORDER BY
    Totaal DESC
我相信这会起作用,但是如果
groupby
给出了
CASE
语句的问题,那么您可能需要将其包装在
MAX
中。不过,这应该不是必需的


我还想看看如何去掉那些列名中的空格。

请仔细阅读如何在SQL中使用s。这是关系数据库的核心概念之一。是否有可能在另一个表中有多行?将from子句更改为“from myreports r left outer join CZ on r.ZiNr=CZ.ZiNr”它将获取CZ表的行,在select中,您可以使用别名max(r.ZiNr)、max(r.eenhide)和sum(CZ.something)等等。hi@Tom No这是不可能的。谢谢