简体   繁体   中英

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. However, one of the colums (ZiNr) is also in the other three tables. I would like at if the ZiNr is in another table that it returns a value in the result set.

Here is my sql statment so far:

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.

Hope I have asked clearly enough.

Thanks in advance

You should be able to just JOIN to the other table. Make sure that you use a LEFT OUTER JOIN , as an INNER JOIN will include only those rows where a match is found. 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.

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 . That shouldn't be necessary though.

I'd also look at getting rid of the spaces in those column names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM