我有2个表要根据日期从中获取计数。换句话说,将从2018年1月1日开始的表格中的所有记录都进行计数,并返回到“计数”列。
我的查询有效,但最终得到2个日期,每个表1个。我最后想要得到的是1个日期,两个表的总计数。
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
, COUNT(*) AS Count
FROM [dwdata].[dbo].SO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
, COUNT(*) AS Count
FROM [dwdata].[dbo].NO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
因此,而不是显示2018年1月1日的记录Count:1 另一条记录显示1/1/2018 Count:2
我只有一条记录,显示1/1/2018 Count:3
答案 0 :(得分:1)
选项可以是联合表和临时表。联合基本上将这两组数据放入同一数据集中,然后您可以将它们与temp表一起计入单个表中。
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
into #table
FROM [dwdata].[dbo].SO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
Union All
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
FROM [dwdata].[dbo].NO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
select DWSTOREDATETIME, COUNT(*)
FROM #table
答案 1 :(得分:1)
您必须获得2个子查询的SUM
的相应日期的UNION
:
SELECT t.DWSTOREDATETIME, SUM(t.Count) AS Count
FROM(
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
, COUNT(*) AS Count
FROM [dwdata].[dbo].SO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
UNION ALL
SELECT CONVERT(varchar(10),DWSTOREDATETIME, 101) AS DWSTOREDATETIME
, COUNT(*) AS Count
FROM [dwdata].[dbo].NO00
WHERE DWSTOREDATETIME > '2018-01-01 00:00:00' AND DWSTOREDATETIME < '2019-01-01 00:00:00'
GROUP BY CONVERT(varchar(10),DWSTOREDATETIME, 101)
) AS t
GROUP BY t.DWSTOREDATETIME