加入3个分组值

时间:2017-03-17 17:49:12

标签: sql

我有3个查询,每个公司的计数,特定月份的行数,3个不同的表,并返回相同的列:qty,month和company_name。

而不是这个我需要返回1个具有相同3列的表,但是qty必须将所有3个分离查询的值相加。

您能否建议加入或执行它的最佳方式,我不会放松执行速度。

以下是其中一个查询的示例,其他2个查询具有完全相同的语法,而只是T_CUSTSK,它们使用T_CUSTSK2T_CUSTSK3

SELECT
    COUNT(*) as qty, 
    DATEPART (MONTH, [start_date]) AS [month], 
    T_SYSCOM.company_name
FROM
    T_CUSTSK
INNER JOIN 
    T_SYSCOM ON T_CUSTSK.company_id = T_SYSCOM.company_id
WHERE
    DATEPART (MONTH, [start_date]) = 12
GROUP BY 
    DATEPART (MONTH, [start_date]), T_SYSCOM.company_name
ORDER BY
    month, qty DESC

2 个答案:

答案 0 :(得分:0)

Union all将结合您的疑问 然后,您可以使用另一个求和的查询来包装语句:

select sum(qty), month, company_name from (
Select count(*) as qty, datepart(month, [start_date]) as [month], T_SYSCOM.company_name
from T_CUSTSK
INNER JOIN T_SYSCOM
ON T_CUSTSK.company_id=T_SYSCOM.company_id
where datepart(month, [start_date])=12
group by datepart(month, [start_date]), T_SYSCOM.company_name
order by month, qty DESC

union all 

<second query>

union all

<third query> )

group by month, company_name

答案 1 :(得分:0)

尝试这样你可以在子查询中对所有T_CUSTSKx表进行UNION,并将该结果与T_SYSCOM表连接一次。 我假设start_date在T_CUSTSK表中

Select count(*) as qty, datepart(month, [start_date]) as [month], T2.company_name
from (
SELECT company_id,start_date FROM T_CUSTSK
UNION ALL
SELECT company_id,start_date FROM T_CUSTSK2
UNION ALL
SELECT company_id,start_date FROM T_CUSTSK3
) T1
INNER JOIN @T_SYSCOM T2
    ON T1.company_id=T2.company_id
where datepart(month, [start_date])=12
group by datepart(month, [start_date]), T2.company_name
order by month, qty DESC

如果有效,请告诉我