我试图从SQL Server中的3个表中获取所有不同的帐号,但似乎我的方式不起作用,有什么建议吗?
SELECT distinct account, max(date_added) as date_added FROM table_one group by account
union
SELECT distinct account, max(date_added) as date_added, FROM table_two group by account
union
SELECT distinct account, max(date_added) as date_added, FROM table_three group by account order by account asc
答案 0 :(得分:4)
SELECT account, MAX(date_added) AS date_added
FROM table_one
GROUP BY account
UNION
SELECT account, MAX(date_added) AS date_added
FROM table_two
GROUP BY account
UNION
SELECT account, MAX(date_added) AS date_added
FROM table_three
GROUP BY account
ORDER BY account ASC
SELECT account, MAX(date_added) AS date_added
FROM (
SELECT account, date_added
FROM table_one
UNION ALL
SELECT account, date_added
FROM table_two
UNION ALL
SELECT account, date_added
FROM table_three
) t
GROUP BY account
ORDER BY account ASC
答案 1 :(得分:1)
生成一组数据,结合结果,然后获取每个帐户的最大日期。这会生成一个内联视图,我们可以从中获取不同的帐户和最大日期。
SELECT account, max(date_Added) as Date_Added from (
SELECT account date_Added FROM table_one
union
SELECT account, date_added FROM table_two
union
SELECT account, date_added FROM table_three) B
Group by account
答案 2 :(得分:0)
select account, MAX(date_added)
FROM (
SELECT account, date_added FROM table_one
union
SELECT account, date_added FROM table_two
union
SELECT account, date_added FROM table_three
) X
group by account
order by account asc
这个查询的作用是,它将来自一个记录集中所有三个表的所有数据联合起来,因此您可以使用它,因为它是一个表。想象一下,你有3个账户,1,2和3,并且有以下数据在这3个表中分布:
Table One
Account | Date Added
--------+-----------
1 | 01-01-2015
2 | 01-02-2015
Table Two
Account | Date Added
--------+-----------
3 | 01-03-2015
1 | 01-02-2015
Table Three
Account | Date Added
--------+-----------
2 | 01-04-2015
3 | 01-05-2015
所以在联合所有这三个表中的所有记录之后,我们得到了以下表格' table' (实际上它是存储在内存中的记录集):
Union Data
Account | Date Added
--------+-----------
1 | 01-01-2015
2 | 01-02-2015
3 | 01-03-2015
1 | 01-02-2015
2 | 01-04-2015
3 | 01-05-2015
我们只为这个集合中的每个不同帐户选择帐户和最新的date_added,因此我们得到以下结果:
Result Data
Account | Date Added
--------+-----------
1 | 01-02-2015
2 | 01-04-2015
3 | 01-05-2015
随意提出与此相关的任何其他问题。
答案 3 :(得分:0)
如果您想要一个包含所有帐户的列表,并且每个帐户只出现一次,那么您可以执行以下操作:
select distinct account from table_one
union
select distinct account from table_two
union
select distinct account from table_three
通过使用union,您将不会获得重复的行,并且由于您只选择了帐户,因此您只能获得每个帐户一次。
然而,目前还不清楚你在使用date_added列做了什么。