0

第一个问题,希望有人可以在这里提供帮助。我一直在努力寻找如何做到这一点,并认为是时候寻求帮助了。请注意我对我的 SQL 查询非常陌生,我的代码可能和它一样不优雅!

我正在使用两个具有相同配置的数据库。每个数据库代表区域数据,但它们之间的所有表和列都是相同的。本质上,我希望获得特定个人执行的每日活动计数。此外,我需要收集的数据位于多个表上,所以请耐心等待我在这里记下:D_USA 和 D_CAN 用于两个数据库,T1 和 T2 用于我要加入的两个表。这是我现有的代码和我得到的输出:

SELECT 
  "USA" AS REGION, 
  LEFT(FROM_UNIXTIME(D_USA.T1.date),10) as DATE,
  D_USA.T1.owner AS OWNER, COUNT(DISTINCT D_USA.T1.id) AS GROUPS, 
  COUNT(DISTINCT D_USA.T2.id) AS UNITS
FROM
  D_USA.T1
  JOIN D_USA.T2 ON D_USA.T1.id = D_USA.T2.parent_id
WHERE
  D_USA.T1.complete='Y'
  AND D_USA.T1.owner = 'XYZ' 
  AND D_USA.T2.status = 'P' 
  AND LEFT(FROM_UNIXTIME(D_USA.T1.date),10) >= '2012-01-01'
GROUP BY DATE
UNION ALL
SELECT 
  "CAN" AS REGION, 
  LEFT(FROM_UNIXTIME(D_CAN.T1.date),10) as DATE,
  D_CAN.T1.owner AS OWNER, 
  COUNT(DISTINCT D_CAN.T1.id) AS GROUPS, 
  COUNT(DISTINCT D_CAN.T2.id) AS UNITS
FROM
  D_CAN.T1
  JOIN D_CAN.T2 ON D_CAN.T1.id = D_CAN.T2.parent_id
WHERE 
  D_CAN.T1.complete='Y'
  AND D_CAN.T1.owner = 'XYZ' 
  AND D_CAN.T2.status = 'P' 
  AND LEFT(FROM_UNIXTIME(D_CAN.T1.date),10) >= '2012-01-01'
GROUP BY DATE 
ORDER BY DATE ASC;

电流输出:

REGION|DATE|OWNER|GROUPS|UNITS
USA|2012-01-01|XYZ|10|100
CAN|2012-01-01|XYZ|5|100
USA|2012-01-02|XYZ|10|75
USA|2012-01-03|XYZ|5|50
CAN|2012-01-03|XYZ|10|50
CAN|2012-01-04|XYZ|10|100

期望的输出(基于以上)

DATE|OWNER|GROUPS|UNITS
2012-01-01|XYZ|15|200
2012-01-02|XYZ|10|75
2012-01-03|XYZ|15|100
2012-01-04|XYZ|10|100

任何帮助将不胜感激!

4

1 回答 1

0

只需将一个选择包裹在它周围

选择 Date,Owner,Groups, Sum(Units) 作为 Units From (在此处插入您的查询) somedummyName Group By Date,Owner,Groups

于 2012-05-17T12:43:19.110 回答