内部联接的SQL替代方法

时间:2017-04-21 14:25:44

标签: sql-server

我有一个表格,其数据显示为:

Staion  Date        Temperature
A      2015-07-31   8
B      2015-07-31   6
C      2015-07-31   8
A      2003-02-21   4
B      2003-02-21   7
C      2003-02-21   7

对于我需要创建数组的每个日期,以便它具有以下组合:

c1 = (A + B)/2, c2 = (A + B + C)/3 and c3 = (B + C)/2

是的,我在桌子上做了三个不同的inner join并做了最后的inner join以获得以下结果:

Date         c1    c2      c3
2015-07-31   7     7.33    7
2003-02-21   5.5   6       7

有更简洁的方法吗?

4 个答案:

答案 0 :(得分:6)

不需要JOIN,您只需使用GROUP BY和汇总功能:

WITH CTE AS
(
    SELECT  [Date],
            MIN(CASE WHEN Staion = 'A' THEN Temperature END) A,
            MIN(CASE WHEN Staion = 'B' THEN Temperature END) B,
            MIN(CASE WHEN Staion = 'C' THEN Temperature END) C
    FROM dbo.YourTable  
    GROUP BY [date]
)
SELECT  [Date],
        (A+B)/2 c1,
        (A+B+C)/3 c2,
        (B+C)/2 c3
FROM CTE;

答案 1 :(得分:3)

SUM在这种情况下,函数非常有用:

SELECT 
    c1 = SUM(CASE WHEN Staion IN ('A', 'B') THEN Temperature ELSE 0 END) / 2,
    c2 = SUM(Temperature) / 3,
    c3 = SUM(CASE WHEN Staion IN ('B', 'C') THEN Temperature ELSE 0 END) / 2,
    [Date]
FROM dbo.Table
GROUP BY [Date]

答案 2 :(得分:2)

你可以只使用两个连接,几乎字面上你提供的公式:

declare @t table (Station char(1) not null,[Date] date not null, Temperature int not null)
insert into @t(Station,[Date],Temperature) values
('A','20150731',8),
('B','20150731',6),
('C','20150731',8),
('A','20030221',4),
('B','20030221',7),
('C','20030221',7)

select
    B.[Date],
    c1 = (A.Temperature + B.Temperature)/2.0,
    c2 = (A.Temperature + B.Temperature + C.Temperature)/3.0,
    c3 = (B.Temperature + C.Temperature)/2.0
from
    @t B
        inner join
    @t A
        on
            B.[Date] = A.[Date]
        inner join
    @t C
        on
            B.[Date] = C.[Date]
where
    A.Station = 'A' and
    B.Station = 'B' and
    C.Station = 'C'

结果:

Date       c1              c2          c3
---------- --------------- ----------- ----------
2015-07-31 7.000000        7.333333    7.000000
2003-02-21 5.500000        6.000000    7.000000

答案 3 :(得分:1)

您可以对透视数据使用透视和计算,如下所示:

select [Date], c1 = (A+B)/2.0, c2 = (A+B+C)/3.0, C3 = (B+C)/2.0 from 
( select * from #yourstation ) s
pivot (max(temparature) for station in ([A], [B], [C])) p

您的输入表:

create table #yourStation (station char(1), date date, Temparature int)

insert into #yourStation (station, date, Temparature) values
 ('A','2015-07-31',   8     )
,('B','2015-07-31',   6     )
,('C','2015-07-31',   8     )
,('A','2003-02-21',   4     )
,('B','2003-02-21',   7     )
,('C','2003-02-21',   7     )