结合3个SQL查询的结果?

时间:2019-02-21 10:04:52

标签: mysql sql sql-server database

尝试合并3个查询的结果时遇到麻烦:

result so far

这是3个查询与union联接的结果,它们都在同一表中选择数据,除了最后一列,我希望将结果放在一行中,在这种情况下,结果为17我无法使其正常运作...有什么想法吗?

谢谢

编辑:这是上面结果中与union一起使用的3个查询的代码:

select distinct SSN_ID, 
            TME_ID, 
            TME_LIBELLE, 
            convert(varchar,ssn_date_debut,103) as 'Debut',
            CONVERT (varchar,ssn_date_fin,103) as 'Fin',
            SSN_NB_JOURS,
            COUNT (atr_id) as 'Total'
from SESSION
join INSCRIPTION on INS_SSN_ID = SSN_ID
join ACTEUR on INS_ATR_ID = ATR_ID
join theme on tme_id = ssn_tme_id
join ETAT_SESSION on esn_id = ssn_esn_id
join LIEU_SESSION on LSN_SSN_ID =ssn_id
join LIEU on LEU_ID = LSN_LEU_ID
where INS_DT_CONVOCATION is not null
and SSN_ESN_ID = 15
    and SSN_JOURNEE_ETUDE = 1 
    and LEU_NOM is not null
    and year(ssn_date_debut) = YEAR(GETDATE())
 group by SSN_ID,TME_ID,TME_LIBELLE,ssn_date_debut,ssn_date_fin,SSN_NB_JOURS,ins_ssn_id

union

 select distinct SSN_ID, 
                TME_ID, 
            TME_LIBELLE, 
            convert(varchar,ssn_date_debut,103) as 'Debut',
            CONVERT (varchar,ssn_date_fin,103) as 'Fin',
            SSN_NB_JOURS,
            COUNT (atr_id) as 'Total'
from SESSION
join SESSION_FORMATEUR on ASN_SSN_ID = SSN_ID 
join ACTEUR anim on  anim.ATR_ID = asn_atr_id
join theme on tme_id = ssn_tme_id
join ETAT_SESSION on esn_id = ssn_esn_id
join LIEU_SESSION on LSN_SSN_ID =ssn_id
join LIEU on LEU_ID = LSN_LEU_ID
where SSN_ESN_ID = 15
    and SSN_JOURNEE_ETUDE = 1 
    and LEU_NOM is not null
    and year(ssn_date_debut) = YEAR(GETDATE())

 group by SSN_ID, TME_ID, 
TME_LIBELLE,ssn_date_debut,ssn_date_fin,SSN_NB_JOURS,asn_ssn_id

 union

  select distinct SSN_ID, 
            TME_ID, 
            TME_LIBELLE, 
            convert(varchar,ssn_date_debut,103) as 'Debut',
            CONVERT (varchar,ssn_date_fin,103) as 'Fin',
            SSN_NB_JOURS,
            COUNT (atr_id) as 'Total'
from SESSION
left join INTERVENANT on ITV_SSN_ID = SSN_ID
left join ACTEUR on ITV_ATR_ID = ATR_ID
join theme on tme_id = ssn_tme_id
join ETAT_SESSION on esn_id = ssn_esn_id
join LIEU_SESSION on LSN_SSN_ID =ssn_id
join LIEU on LEU_ID = LSN_LEU_ID
where SSN_ESN_ID = 15
and SSN_JOURNEE_ETUDE = 1 
and LEU_NOM is not null
and year(ssn_date_debut) = YEAR(GETDATE())

 group by SSN_ID, TME_ID, 
TME_LIBELLE,ssn_date_debut,ssn_date_fin,SSN_NB_JOURS,ITV_SSN_ID

2 个答案:

答案 0 :(得分:2)

一种派生的查询方法来获取总计列的SUM:

SELECT SSN_ID, TIME_ID, TIME_LIBELLE, DEBUT, FIN, SSN_NB_JOURS, SUM(Total) as Total
FROM
(
-- Your original SELECT with UNION
SELECT .. FROM ..
UNION ALL
SELECT .. FROM ..
UNION ALL
SELECT .. FROM ..
) d
GROUP BY SSN_ID, TIME_id, TIME_LIBELLE, DEBUT, FIN, SSN_NB_JOURS

这种方式在mysql和sql服务器上都应该是有效的语法

答案 1 :(得分:0)

用作

选择( 从表中选择唯一的(除最后一个以外的所有列),(从表中选择sum(总计))