0

我使用 SQL 进行简单查询,但现在需要执行一些更复杂的操作。我不确定如何嵌套查询。

我有一张包含以下列的表格:

Date, Daily Power, Daily Power 1, Daily power2

我需要找到它max daily values,然后按月过滤。我也需要Daily Power 1Daily Power 2总结成一个新的专栏。

任何帮助,将不胜感激。

4

2 回答 2

1

您的表的部分问题是数据未标准化,因为您有 3 列,每列都包含一个单独的值DailyPower

您可以轻松获得所需结果的一种方法是使用查询对数据进行反透视。UNION ALL

此查询将从多列中获取数据并将其转换为多行以供使用:

select date, 'DailyPower' as col, DailyPower as value
from yourtable
union all
select date, 'DailyPower1' as col, DailyPower1 as value
from yourtable
union all
select date, 'DailyPower2' as col, DailyPower2 as value
from yourtable

请参阅SQL Fiddle with Demo。此查询获取数据并将其转换为结果:

|       DATE |         COL | VALUE |
------------------------------------
| 2012-01-01 |  DailyPower |   456 |
| 2012-01-02 |  DailyPower |   789 |
| 2012-02-01 |  DailyPower |    23 |
| 2012-01-01 | DailyPower1 |   789 |
| 2012-01-02 | DailyPower1 |   235 |
| 2012-02-01 | DailyPower1 |    89 |
| 2012-01-01 | DailyPower2 |    65 |
| 2012-01-02 | DailyPower2 |    45 |
| 2012-02-01 | DailyPower2 |    10 |

一旦数据在行中,就更容易max()按日期获取值。

您的查询将类似于以下内容:

select date, 
  max(value) MaxDailyPower,
  sum(case when col in ('DailyPower1', 'DailyPower2') then value end) TotalDailyPower
from
(
  select date, 'DailyPower' as col, DailyPower as value
  from yourtable
  union all
  select date, 'DailyPower1' as col, DailyPower1 as value
  from yourtable
  union all
  select date, 'DailyPower2' as col, DailyPower2 as value
  from yourtable
) src
where date >= '2012-01-01' 
  and date <= '2012-12-31'
group by date

请参阅SQL Fiddle with Demo。这给出了结果:

|       DATE | MAXDAILYPOWER | TOTALDAILYPOWER |
------------------------------------------------
| 2012-01-01 |           789 |             854 |
| 2012-01-02 |           789 |             280 |
| 2012-02-01 |            89 |              99 |

编辑#1,如果你想GROUP BY一个月,那么你可以使用:

select month(date) Month, 
  max(value) MaxDailyPower,
  sum(case when col in ('DailyPower1', 'DailyPower2') then value end) TotalDailyPower
from
(
  select date, 'DailyPower' as col, DailyPower as value
  from yourtable
  union all
  select date, 'DailyPower1' as col, DailyPower1 as value
  from yourtable
  union all
  select date, 'DailyPower2' as col, DailyPower2 as value
  from yourtable
) src
group by month(date)

请参阅带有演示的 SQL Fiddle

于 2013-02-04T11:36:51.037 回答
0

这是你想要的吗?

select date,
       (case when DailyPower > DailyPower1 and DailyPower > DailyPower2 then DailyPower
             when DailyPower1 > DailyPower2 then DailyPower1
             else DailyPower2
       ) as MaxDailyPower,
       coalesce(DailyPower1, 0) + Colaesce(DailyPower2) as DailyPowerSUm
from t
where date between '2012-01-01' and '2012-03-31'  -- for the filter

这假设您的数据中每个日期都有一行。

于 2013-02-03T22:44:47.383 回答