如何按ID列更正分组-SQL

时间:2018-10-25 09:00:22

标签: sql sql-server tsql group-by scale

我有这个查询:

(
 SELECT DISTINCT 
   qdb.driver AS driver, 
   d.queno AS queno 
 FROM quotedb AS qdb 
 LEFT JOIN drivers AS d ON qdb.driver = d.id
)
UNION ALL
(
 SELECT DISTINCT 
   p.driver AS driver, 
   d.queno AS queno 
 FROM packaging AS p 
 LEFT JOIN drivers AS d ON p.driver = d.id 
)
ORDER BY 
  (CASE WHEN queno = '' OR queno IS NULL THEN 1 
   ELSE 0
   END)

我不知道为什么,但是此查询无法缩放重复的TwI_TwrId。

我有这个结果:

Look Here

2 个答案:

答案 0 :(得分:0)

由于TwI_TwrId每个都有唯一的TwI_TwIId,因此您需要将它们从group by子句中排除:

SELECT TwI_TwrId, TwI_MagId,
       SUM(TwI_Ilosc) AS Ilosc,
       SUM(TwI_Wartosc) AS Wartosc,
       SUM(TwI_Braki) AS Braki,
       SUM(TwI_Rezerwacje) AS Rezerwacje,
       SUM(TwI_Zamowienia) AS Zamowienia
FROM cdn.TwrIlosci
WHERE twi_magid = 1
GROUP BY TwI_TwrId, TwI_MagId;

答案 1 :(得分:0)

您的语句给出了三列TwI_TwrId,TwI_TwIId,TwI_MagId的独特组合,如果要删除TwI_TwrId的重复项,请运行以下内容

SELECT 
       TwI_TwrId,
       TwI_MagId,
       SUM(TwI_Ilosc) AS Ilosc,
       SUM(TwI_Wartosc) AS Wartosc,
       SUM(TwI_Braki) AS Braki,
       SUM(TwI_Rezerwacje) AS Rezerwacje,
       SUM(TwI_Zamowienia) AS Zamowienia
FROM cdn.TwrIlosci
WHERE twi_magid = 1
GROUP BY TwI_TwrId,
         TwI_MagId