获取链接到第三个表

时间:2016-02-16 10:57:26

标签: sql sql-server tsql

正如标题中所提到的,我希望有最佳查询来执行以下操作:没有SUBQUERIES

我有这个 enter image description here

所以这里,每个客户都有命令(订单) 每个客户都有事实(账单) 并且账单包含命令(订单),账单和订单金额在MontantCommande和MontantFacture中。

所以在这里我需要获得订单总数(MontantCommande)的总和以及每个客户的账单Facture(MontantFacture)的总和。

我尝试了以下但是得到了错误的结果

  SELECT cl.idClient
  ,SUM(cm.MontantCommande) AS TotalCommande 
  ,SUM(f.MontantFacture) AS TotalFacture
  FROM client cl
  INNER JOIN commande cm ON cl.idClient = cm.idClientCommande
  INNER JOIN facture f ON cl.idclient = f.idclientFacture
  GROUP BY cl.IdClient

我该怎么做?

编辑: 这里是我的查询结果,从所有相关表中选择

enter image description here

总和结果在这里是错误的,因为你可以看到它必须是

1050年至1610年

680-750

600-1000

编辑2:我要提到我需要在没有子查询的情况下这样做。感谢

4 个答案:

答案 0 :(得分:2)

您可以使用相关的子查询,如下所示:

HANDLE hFile = CreateFileA(
     filePath.c_str(),
     GENERIC_WRITE,
     0,
     NULL,
     CREATE_ALWAYS,
     FILE_ATTRIBUTE_NORMAL| FILE_FLAG_WRITE_THROUGH ,
     NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
     throw MyException("CreateFile failed");
}

DWORD bytesWritten = 0;
auto errorFlag = WriteFile(
     hFile,
     data.data(),
     static_cast<DWORD>(data.size()),
     &bytesWritten,
     NULL);
if (bytesWritten != data.size() || errorFlag != TRUE)
{
     CloseHandle(hFile);
     throw MyException("WriteFile failed" + std::to_string(GetLastError()));
}

auto ret = FlushFileBuffers(hFile);
if (!ret)
{
     CloseHandle(hFile);
     throw MyException("FlushFileBuffers failed");
}

CloseHandle(hFile);

// The file isn't written to the disk yet!!!

或者加入:

SELECT t.idClient,
       (select sum(s.montantcommande) from Commande s
        Where t.idClient = s.idClientCommande) as TotalCommande,
       (select sum(f.montantfactore) from Facture f
        Where t.idClient = f.idClientFacture) as TotalFacture
FROM Client t

答案 1 :(得分:0)

请使用此查询

SELECT idClient,SUM(MontantCommande) AS TotalCommande ,
SUM(MontantFacture) AS TotalFacture from  client c
Inner join  commande a  on c.IdClient = a.idClientCommande
inner join  facture b on a.IdCommande = b.IdCommandFacture AND a.idClientCommande = b.idclientFacture
group by idClient

答案 2 :(得分:-2)

试试这个:

SELECT cl.idClient, SUM(IIF(ISNULL(cm.MontantCommande),0,cm.MontantCommande)) AS TotalCommande, SUM(IIF(ISNULL(f.MontantFacture),0,f.MontantFacture)) AS TotalFacture
FROM client cl
INNER JOIN commande cm ON cl.idClient = cm.idClientCommande
INNER JOIN facture f ON cl.idclient = f.idclientFacture
GROUP BY cl.IdClient

答案 3 :(得分:-3)

你可以把你的Insert语句放在本地我可以试试吗?