包含聚合的多个查询的结果

时间:2012-05-17 02:50:53

标签: sql sql-server tsql

我有2个单独的select语句,每个语句都使用聚合函数。我希望能够得出结果并将它们结合起来。

table_a
id int
entered_date datetime (holds utc stamp)
balance money
group_id int

table_b
id int
entered_date date
balance money
transaction_type int

query 1: 
select convert(date,entered_date), sum(balance) as earned
from table_a
where group_id in (1, 2, 3, 4)
group by convert(date,entered_Date)

query 2: 
select convert(date,entered_date), sum(balance) as spent
where transaction_type = 2
group by convert(date,entered_Date)

results:
query 1:
2012-05-13, 5000
2012-05-14, 12000
...

query 2:
2012-05-13, 9000
2012-05-14, 55856
...

我想在不使用临时表的情况下为每条记录返回一行。结果集应该有一个日期,然后是赢得与花费。我有一个使用union运行的报告来获取总数,这很好,但是我需要生成一个包含1条记录和一条vs vs line的结果集。对此有任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:0)

尝试:

;With AllDates AS
(
select convert(date,entered_date) As EnteredDate
    from table_a
    where group_id in (1, 2, 3, 4)
    group by convert(date,entered_Date)
UNION
select convert(date,entered_date)
    from table_b
    where transaction_type = 2
    group by convert(date,entered_Date)
)
, AllEarned AS (
select convert(date,entered_date) AS EnteredDate, sum(balance) as Earned
    from table_a
    where group_id in (1, 2, 3, 4)
    group by convert(date,entered_Date)
)
, AllSpent AS (
select convert(date,entered_date) AS EnteredDate, sum(balance) as Spent
    from table_b
    where transaction_type = 2
    group by convert(date,entered_Date)
)
SELECT
    d.EnteredDate, e.Earned, s.Spent
    FROM AllDates d
    LEFT OUTER JOIN AllEarned e ON d.EnteredDate=e.EnteredDate
    LEFT OUTER JOIN AllSpent s ON d.EnteredDate=s.EnteredDate
    ORDER BY 1,2,3

答案 1 :(得分:0)

SELECT 
       CASE WHEN a.a_date IS NULL THEN b.a_date ELSE a.a_date END as a_data, 
       a.earned,
       b.spent
FROM
    (select 
         convert(date,entered_date) as a_date, 
         sum(balance) as earned
    from table_a
    where group_id in (1, 2, 3, 4)
    group by entered_Date) A
FULL OUTER JOIN 
   (select 
        convert(date,entered_date) as a_date, 
        sum(balance) as spent
    from table_a
    where transaction_type = 2
    group by entered_Date) B 
ON A.a_date=b.a_date

如果有数据不符合这两个条件,请使用FULL OUTER JOIN。并使用CASE WHEN a.a_date IS NULL THEN b.a_date ELSE a.a_date END as a_data

答案 2 :(得分:0)

您可以使用逻辑组合这些,假设两者都来自同一个表  (第二个查询缺少from语句):

select convert(date,entered_date),
       sum(case when group_id in (1, 2, 3, 4) then balance end) as earned,
       sum(case when transaction_type = 2 then balance end) as spend
from table_a
group by convert(date,entered_Date) 

答案 3 :(得分:0)

假设赚取的金额来自table_a,消费金额来自table_b,

; WITH a AS (
    select entered_date=convert(date,entered_date), balance as earned, 0 AS spent
    from table_a
    where group_id in (1, 2, 3, 4)
    UNION ALL
    select entered_date=convert(date,entered_date), 0 AS earned, balance as spent
    from table_b
    where transaction_type = 2
)
SELECT entered_date
, earned=SUM(earned)
, spent=SUM(spent)
FROM a
GROUP BY entered_date