我想在select语句中使用子查询。类似的东西:
SELECT
(SELECT COUNT(*) FROM table2 WHERE a = '1') AS countsubquery, fielda,fieldb
FROM testtable
WHERE a = 'b'
但是当子查询为空时,整行将从结果中删除。因此,当subquery = null并填充fielda en字段b时,此行将从结果中删除,因为countsubquery = null。
结果是否有办法:
countsubquery = null
fielda = filled
fieldb = filled
在我的情况下,子查询需要在select语句中。
谢谢!
**编辑** 真实查询:
SELECT (driver.[Initials]+' '+driver.[Driver Name]) AS bedrijdernaam,
driver.[Function] AS functie,
leasecardriver.[Driver Code] AS personeelsnummer,
leasecar.[Car Brand Code] AS automerk,
leasecar.[Car Type Code] AS autotype,
leasecar.[License No_] AS kenteken,
(SELECT SUM(fuel.Amount) FROM [EXAMPLEDATA$Fuel Table] AS fuel
WHERE fuel.[Perpetration Date] >= '--01 00:00:00'
AND fuel.[Perpetration Date] <= '--29 11:59:00'
AND fuel.personnelnumber = leasecardriver.[Driver Code]) AS verbruik,
leasecardriver.[Driver Code] AS personeelsnummer1,
CONVERT(VARCHAR(19),leasecontract.[Expected Contract ending date],105) AS einddatum
FROM [EXAMPLEDATA$Lease Contract] AS leasecontract
LEFT JOIN [EXAMPLEDATA$Lease Car] AS leasecar ON leasecontract.[License No_] = leasecar.[License No_]
LEFT JOIN [EXAMPLEDATA$Lease Company] AS leasecompany ON leasecompany.Code = leasecontract.[Lease Company Code]
LEFT JOIN [EXAMPLEDATA$Lease Car Driver] AS leasecardriver ON leasecardriver.license = leasecar.[License No_]
LEFT JOIN [EXAMPLEDATA$Driver] AS driver ON leasecardriver.[Driver Code] = driver.[Driver]
WHERE (leasecontract.[Status] = '0' OR leasecontract.[Status] = '1')
AND (((driver.[Voornaam]+' '+driver.[Driver Name]) LIKE '%%') OR (leasecar.[License No_] LIKE '%%') OR (driver.[Cost place code] LIKE '%%') OR (driver.[BusinessLine (GP)] LIKE '%%') OR (driver.[Salaris Unit (GP)] LIKE '%%') OR (leasecardriver.[Driver Code] LIKE '%%'))
以下是“租车。[许可证号_] AS肯特肯”,
答案 0 :(得分:0)
如果我有代表,请将此添加为评论。
如果我理解正确,语法会继续,但是你遇到了子查询结果为null的记录问题。在这种情况下,我认为值得一看: http://msdn.microsoft.com/en-us/library/ms184325.aspx
如果结果为NULL,您可以指定备用值,因此这也应显示在结果集中。
答案 1 :(得分:0)
试试这个:
SELECT
COALESCE((SELECT COUNT(*) FROM table2 WHERE a = '1'),0) AS countsubquery,
fielda,fieldb
FROM testtable
WHERE a = 'b'