首页 > 其他 > 详细

联合查询(姑且称之为联合查询)的最差解

时间:2019-06-27 14:46:57      阅读:125      评论:0      收藏:0      [点我收藏+]

1.数据如下

TimePoint PollutantCode StatusName Value
2019-03-16 01:00:00.000 PM10 大气温度 11.096
2019-03-16 01:00:00.000 PM10 大气压力 102.354
2019-03-16 01:00:00.000 PM2.5 大气温度 14.525
2019-03-16 01:00:00.000 PM2.5 大气压力 101.358
2019-03-16 02:00:00.000 PM10 大气温度 10.134
2019-03-16 02:00:00.000 PM10 大气压力 102.312
2019-03-16 02:00:00.000 PM2.5 大气温度 13.883
2019-03-16 02:00:00.000 PM2.5 大气压力 101.3
2019-03-16 03:00:00.000 PM10 大气温度 10.368
2019-03-16 03:00:00.000 PM10 大气压力 102.249
2019-03-16 03:00:00.000 PM2.5 大气温度 14.033
2019-03-16 03:00:00.000 PM2.5 大气压力 101.258

2.要求

12条数据可以变成3条数据,并且列变成(TimePoint,PM2_5大气温度,PM2_5大气压力,PM10大气温度,PM10大气压力)

3.建表

IF OBJECT_ID('tempdb..#TestTable') IS NOT NULL
    DROP TABLE #TestTable;

CREATE TABLE #TestTable
(
    Id INT IDENTITY(1,1),  
    TimePoint DATETIME, 
    PollutantCode VARCHAR(10),
    StatusName NVARCHAR(50),
    Value VARCHAR(50)
)

INSERT INTO #TestTable(TimePoint,PollutantCode,StatusName,Value)
SELECT       '2019-03-16 01:00:00.000','PM10', '大气温度','11.096'
UNION SELECT '2019-03-16 01:00:00.000' , 'PM10','大气压力','102.354'
UNION SELECT '2019-03-16 01:00:00.000' , 'PM2.5','大气温度','14.525'
UNION SELECT '2019-03-16 01:00:00.000' , 'PM2.5','大气压力','101.358'
UNION SELECT '2019-03-16 02:00:00.000' , 'PM10','大气温度','10.134'
UNION SELECT '2019-03-16 02:00:00.000' , 'PM10','大气压力','102.312'
UNION SELECT '2019-03-16 02:00:00.000' , 'PM2.5','大气温度','13.883'
UNION SELECT '2019-03-16 02:00:00.000' , 'PM2.5','大气压力','101.3'
UNION SELECT '2019-03-16 03:00:00.000' , 'PM10','大气温度','10.368'
UNION SELECT '2019-03-16 03:00:00.000' , 'PM10','大气压力','102.249'
UNION SELECT '2019-03-16 03:00:00.000' , 'PM2.5','大气温度','14.033'
UNION SELECT '2019-03-16 03:00:00.000' , 'PM2.5','大气压力','101.258'

4.Show your the code(最差解)

SELECT a.TimePoint,a.Value PM2_5大气温度,b.Value PM2_5大气压力,d.Value PM10大气温度,c.Value PM10大气压力
FROM
(
    SELECT *
    FROM #TestTable
    WHERE StatusName = '大气温度'
          AND PollutantCode = 'PM2.5'
) a
    LEFT JOIN
    (
        SELECT *
        FROM #TestTable
        WHERE StatusName = '大气压力'
              AND PollutantCode = 'PM2.5'
    ) b
        ON a.TimePoint = b.TimePoint
     LEFT JOIN
    (
        SELECT *
        FROM #TestTable
        WHERE StatusName = '大气压力'
              AND PollutantCode = 'PM10'
    ) c
        ON a.TimePoint = c.TimePoint
     LEFT JOIN
    (
        SELECT *
        FROM #TestTable
        WHERE StatusName = '大气温度'
              AND PollutantCode = 'PM10'
    ) d
        ON a.TimePoint = d.TimePoint

5.这种不知道算不算行转列...应该有更好的解决方案...期待有缘人可以解答...

联合查询(姑且称之为联合查询)的最差解

原文:https://www.cnblogs.com/Mysdm/p/11096790.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!