开发者

Union Select Column Mismatch

Here's my query:

SELECT
    FROM_UNIXTIME( date_added,  '%m-%d-%Y' ) AS formatted_date开发者_如何学Python,
    SUM( tb =1 ) AS sum_users,
    SUM( tb =2 ) AS sum_links,
    SUM( tb =3 ) AS sum_ads,
    SUM( tb =4 ) AS sum_actions
FROM (
    SELECT date_added, 1 AS tb
        FROM users_list WHERE 1=1
    UNION ALL 
    SELECT date_added, 2
        FROM users_links WHERE 1=1
    UNION ALL 
    SELECT date_served, 3
        FROM ads_served WHERE 1=1
    UNION ALL 
    SELECT date_served, 4
        FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC

Here's my table data:

users_list

id    date_added
1     1234567890
2     1334567890
3     1434567890

users_links

id    date_added
1     1244567890
2     1354567890
3     1464567890

ads_served

id    date_served    revenue
1     1234567891     0.01
2     1334567892     0.02
3     1434567893     0.02

actions

id    date_served
1     1234561890
2     1334562890
3     1434563890

I am trying to sum the revenue for formatted_date in the ads_served table as a 6th column for the output query. I am lost as to where to start. If I add the sum(revenue) to the union select I get a "column mismatch" error.


Column revenue belongs to ads_served but you are selecting from a sub query where revenue is not present. Add it to the subquery:

SELECT
    FROM_UNIXTIME( date_added,  '%m-%d-%Y' ) AS formatted_date,
    SUM( tb =1 ) AS sum_users,
    SUM( tb =2 ) AS sum_links,
    SUM( tb =3 ) AS sum_ads,
    SUM( tb =4 ) AS sum_actions,
    SUM( revenue ) As sum_revenue
FROM (
    SELECT date_added, 1 AS tb, 0 As revenue
        FROM users_list WHERE 1=1
    UNION ALL 
    SELECT date_added, 2, 0
        FROM users_links WHERE 1=1
    UNION ALL 
    SELECT date_served, 3, revenue
        FROM ads_served WHERE 1=1
    UNION ALL 
    SELECT date_served, 4, 0
        FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC


Try in this way. Why do you use 1=1 ?

SELECT
    FROM_UNIXTIME( date_added,  '%m-%d-%Y' ) AS formatted_date,
    SUM( tb =1 ) AS sum_users,
    SUM( tb =2 ) AS sum_links,
    SUM( tb =3 ) AS sum_ads,
    SUM( tb =4 ) AS sum_actions,
    sum(total) as tot_rev
FROM (
    SELECT date_added,'' as total, 1 AS tb
        FROM users_list WHERE 1=1
    UNION ALL 
    SELECT date_added,'', 2
        FROM users_links WHERE 1=1
    UNION ALL 
    SELECT date_served,revenue, 3
        FROM ads_served WHERE 1=1
    UNION ALL 
    SELECT date_served,'', 4
        FROM actions WHERE 1=1
) AS t
GROUP BY formatted_date
ORDER BY formatted_date DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜