Postgres DISTINCT到单行

时间:2018-12-12 14:31:54

标签: sql postgresql

如何区分为单行

这是我的代码:


SELECT 
wagon.name w_name,
'' as su_name,
'' as m_name,
'' as sk_name,
'' as p_name,
'' as b_name,
'' as o_name,
total w_total,
0 as su_total,
0 as m_total,
0 as sk_total,
0 as p_total,
0 as b_total,
0 as o_total

FROM wagoning 
LEFT JOIN wagon ON wagoning.wagon_id = wagon.id 

UNION ALL

SELECT 

'' w_name,
name su_name,
'' m_name,
'' sk_name,
'' p_name,
'' b_name,
'' o_name,
0 w_total,
total su_total,
0 m_total,
0 sk_total,
0 p_total,
0 b_total,
0 o_total

FROM drying 
LEFT JOIN drier ON drying.drier_id = drier.id 

UNION ALL

SELECT 

'' w_name,
'' su_name,
quantity::varchar as m_name,
'' sk_name,
'' p_name,
'' b_name,
'' o_name,
0 w_total,
0 su_total,
total m_total,
0 sk_total,
0 p_total,
0 b_total,
0 o_total

FROM
bagging

UNION ALL

SELECT 

'' w_name,
'' su_name,
'' m_name,
quantity::varchar as sk_name,
'' p_name,
'' b_name,
'' o_name,
0 w_total,
0 su_total,
0 m_total,
total sk_total,
0 p_total,
0 b_total,
0 o_total


FROM
storing

UNION ALL

SELECT 

'' w_name,
'' su_name,
'' m_name,
'' sk_name,
quantity::varchar as p_name,
'' b_name,
'' o_name,
0 w_total,
0 su_total,
0 m_total,
0 sk_total,
total p_total,
0 b_total,
0 o_total

FROM
processing

UNION ALL

SELECT 

'' w_name,
'' su_name,
'' m_name,
'' sk_name,
'' p_name,
quantity::varchar as b_name,
'' o_name,
0 w_total,
0 su_total,
0 m_total,
0 sk_total,
0 p_total,
quantity * net b_total,
0 o_total

FROM
boxing

UNION ALL

SELECT 

'' w_name,
'' su_name,
'' m_name,
'' sk_name,
'' p_name,
'' b_name,
'' o_name,
0 w_total,
0 su_total,
0 m_total,
0 sk_total,
0 p_total,
0 b_total,
part o_total

FROM
boxing

请检查以下屏幕截图:最佳结果(红色上方)现在如何工作。我想要的是单行中的红线下方

screenshot

1 个答案:

答案 0 :(得分:1)

我想您希望MAX胜过所有UNION ALL的查询结果

select MAX(w_name) as w_name,
       MAX(su_name)as su_name,
      -- ..  other columns

FROM
(
SELECT 
wagon.name w_name,
'' as su_name,
'' as m_name,
'' as sk_name,
'' as p_name,
'' as b_name,
'' as o_name,
total w_total,
0 as su_total,
0 as m_total,
0 as sk_total,
0 as p_total,
0 as b_total,
0 as o_total

FROM wagoning 
LEFT JOIN wagon ON wagoning.wagon_id = wagon.id 

UNION ALL

SELECT 
..