合并SQL中2个表的查询和数据

时间:2013-02-17 22:13:01

标签: sql sql-server-2008

我需要2个表来查询不同的数据。常用链接是datetime列。我试图合并查询,但不断收到各种错误......

最终查询应该给我:date, Peak Power each Day, KWHOpenHrs, KWHClosedTotal

感谢任何帮助。

下面的两个表格

Peak KVA

Date | Power_Apparent_Total

查询:

SELECT
   CAST(t.HD as DATE), MAX(t.Power_Apparent_Total) as 'Peak Power Each Day'
FROM [Peak kVA] t
GROUP BY CAST(t.HD AS DATE)

Daily Consumption

Date | KWH Open | KWH ClosedandOccupied | KWH ClosedandnotOccupied

查询:

select date, 
max(value) kWhOpenHrs,
sum(case when col in ('zkWhClsedAndOccupied', 'zkWhClsedAndNotOccupied') then value   end) kWhClsedTotal
from 
(
  select date, 'zkWhOpenHrs' as col, kWhOpenHours as value
  from dbo.tblDailyPowerConsumption
  union all
  select date, 'zkWhClsedAndNotOccupied' as col, kWhClosedAndNotOccupied as value
  from dbo.tblDailyPowerConsumption
  union all
  select date, 'zkWhClsedAndOccupied' as col, kWhClosedAndOccupied as value
  from dbo.tblDailyPowerConsumption
) src
WHERE MONTH(date) = '12' 
group by date

2 个答案:

答案 0 :(得分:0)

开始执行此请求。您的日期类型不仅包含日期,还包含时间

SELECT [Peak kVA].HD AS [date], [Peak kVA].Power_Apparent_Total,
       tblDailyPowerConsumption.kWhOpenHours, 
       tblDailyPowerConsumption.kWhClosedAndOccupied, 
       tblDailyPowerConsumption.kWhClosedAndNotOccupied 
FROM dbo.[Peak kVA] LEFT JOIN dbo.tblDailyPowerConsumption 
                      ON CAST([Peak kVA].HD AS date) = CAST(tblDailyPowerConsumption.Date AS date) 
                        AND MONTH(tblDailyPowerConsumption.Date) = '12'

答案 1 :(得分:0)

select date, [Peak Power each Day], KWHOpenHrs, KWHClosedTotal
from
   (SELECT
        CAST(t.HD as DATE), MAX(t.Power_Apparent_Total) as 'Peak Power Each Day'
    FROM [Peak kVA] t
    GROUP BY CAST(t.HD AS DATE)) peak
inner join
   (select date, 
    max(value) kWhOpenHrs,
    sum(case when col in 
       ('zkWhClsedAndOccupied', 'zkWhClsedAndNotOccupied') 
       then value end) kWhClsedTotal
   from 
   (
   select date, 'zkWhOpenHrs' as col, kWhOpenHours as value
   from dbo.tblDailyPowerConsumption
   union all
   select date, 'zkWhClsedAndNotOccupied' as col, kWhClosedAndNotOccupied as value
   from dbo.tblDailyPowerConsumption
   union all
   select date, 'zkWhClsedAndOccupied' as col, kWhClosedAndOccupied as value
   from dbo.tblDailyPowerConsumption
   ) src
   WHERE MONTH(date) = '12' 
   group by date) daily
on peak.date = daily.date