计算来自不同表的两列的记录

时间:2014-08-21 15:37:24

标签: sql-server join count multiple-columns

所以我有这个:

select count(InvoiceUniqueness) as [Nbr], CONVERT(varchar(12), ProcessDate, 101) as [Date]
from PreProcessTransLog
where (CONVERT(DATETIME, ProcessDate, 102)) >= dateadd (m,-24,getdate()) and CONVERT(DATETIME, ProcessDate, 120) <= GETDATE() 
and InitialStatus =2
group by CONVERT(varchar(12), ProcessDate, 101)
order by CAST (CONVERT(varchar(12), ProcessDate, 101) as smalldatetime) desc

我想从PreProcessTransLog表中计算InvoiceUniqueness列下的记录,并从另一个名为Ex_Manual_Bill_Header的表中计算(不在代码中的列)ManualBillHeaderID下的记录。我想在名为Nbr的新列中显示计数结果。所以简单来说,我可以说T1中的column1和T2中的column2。 column1有10条记录,column2有5条。我想将两个列连接成一个,这样我就可以显示15条记录。请记住,列具有不同的名称。希望我解释自己

3 个答案:

答案 0 :(得分:0)

如果我准确理解您的请求,我会做这样的事情。

计算每个表的计数,并将结果与​​UNION ALL合并,将其包装在子查询中,并SUM()生成的计数。

declare @table1 table (id int identity(1,1), recorddate datetime)
declare @table2 table (id int identity(1,1), otherdate datetime)

insert into @table1 
select '2014-08-01' union all
select '2014-08-01'


insert into @table2
select '2014-08-01' union all
select '2014-08-02'

select SUM(num), recorddate
from (select COUNT(1) num, recorddate
        from @table1
        group by recorddate

        union all

        select COUNT(1) num, otherdate 
        from @table2
        group by otherdate ) x
group by recorddate     

如果您希望结果分开,请将最后一个查询更改为:

select COUNT(*) num, recorddate
from @table1
group by recorddate
union all
select COUNT(*) num, otherdate 
from @table2
group by otherdate 

答案 1 :(得分:0)

尝试使用UNION ALL。例如:

SELECT COUNT(Column1) AS [Nbr]
FROM Table1
GROUP BY ColumnToGroupOn1

UNION ALL

SELECT COUNT(Column2)
FROM Table2
GROUP BY ColumnToGroupOn2

或者如果您想要包含日期列:

SELECT COUNT(Column1) AS [Nbr], ColumnToGroupOn1 AS [Date]
FROM Table1
GROUP BY ColumnToGroupOn1

UNION ALL

SELECT COUNT(Column2), ColumnToGroupOn2
FROM Table2
GROUP BY ColumnToGroupOn2

答案 2 :(得分:0)

尝试这样的事情:

    SELECT
    COALESCE(t1.[Date], t2.[Date]) AS [Date],
    ISNULL(t1.Nbr, 0), + ISNULL(t2.Nbr, 0) AS Total
FROM
    (
        SELECT COUNT(InvoiceUniqueness) AS [Nbr], CONVERT(VARCHAR(12), ProcessDate, 101) AS [Date]
        FROM PreProcessTransLog
        WHERE (CONVERT(DATETIME, ProcessDate, 102))>=DATEADD(m, -24, GETDATE()) AND CONVERT(DATETIME, ProcessDate, 120)<=GETDATE() AND InitialStatus=2
        GROUP BY CONVERT(VARCHAR(12), ProcessDate, 101)
        --ORDER BY [Date]
    ) t1,
    FULL JOIN (
        SELECT COUNT(ManualBillHeaderID ) AS [Nbr], CONVERT(VARCHAR(12), ProcessDate, 101) AS [Date]
        FROM <whatever table>
        WHERE (CONVERT(DATETIME, ProcessDate, 102))>=DATEADD(m, -24, GETDATE()) AND CONVERT(DATETIME, ProcessDate, 120)<=GETDATE() AND InitialStatus=2
        GROUP BY CONVERT(VARCHAR(12), ProcessDate, 101)
        --ORDER BY [Date]
    ) t2 ON t1.[Date] = t2.[Date]
ORDER BY
    COALESCE(t1.[Date], t2.[Date])