[英]SQL query to add to result list when item is found in another table
I have four tables in my database. 我的数据库中有四个表。 I have a sql statement which gives me the right result for the main table as I need to count and sum some of the returned colums. 我有一条sql语句,可以为我的主表提供正确的结果,因为我需要计算和求和一些返回的列。 However, one of the colums (ZiNr) is also in the other three tables. 但是,其他三个表中也有一个列(ZiNr)。 I would like at if the ZiNr is in another table that it returns a value in the result set. 我想知道ZiNr是否在另一个表中,它在结果集中返回一个值。
Here is my sql statment so far: 到目前为止,这是我的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
I need to find out if the ZiNr is in another table called CZ and append a value called CZ to that row. 我需要找出ZiNr是否在另一个名为CZ的表中,并将一个名为CZ的值附加到该行。
Hope I have asked clearly enough. 希望我已经问清楚了。
Thanks in advance 提前致谢
You should be able to just JOIN
to the other table. 您应该可以只JOIN
另一个表。 Make sure that you use a LEFT OUTER JOIN
, as an INNER JOIN
will include only those rows where a match is found. 确保使用LEFT OUTER JOIN
,因为INNER JOIN
将仅包括找到匹配项的那些行。 Then you can simply check one of the columns from that table to see if a match was found (it needs to be a column that otherwise can't be NULL
though. 然后,您可以简单地检查该表中的一列以查看是否找到匹配项(它必须是一列,否则该列不能为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
I believe that will work, but if the GROUP BY
gives problems with the CASE
statement then you might need to wrap that in a MAX
. 我相信这会起作用,但是如果GROUP BY
在CASE
语句中出现问题,那么您可能需要将其包装在MAX
。 That shouldn't be necessary though. 但这不是必需的。
I'd also look at getting rid of the spaces in those column names. 我还希望摆脱那些列名称中的空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.