SQL Server:根据列中的日期返回最新记录

时间:2018-10-25 04:16:32

标签: sql sql-server tsql group-by inner-join

我在使用基本查询时遇到问题,我的临时表有一个主键和一个名为server { listen 443; server_name MY_SITE.com; return 301 https://www.MY_SITE.com$request_uri; } server { # Ipv4 # IPv6 # listen [::]:80; # SSL Ipv4 & v6 # listen 443 default_server ssl; # listen [::]:443 ssl; # ssl_session_timeout 24h; # ssl_session_cache shared:SSL:10m; # ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:RSA+3DES:AES128-SHA:!ADH:!AECDH:!MD5; # ssl_prefer_server_ciphers on; # Do not forget to create this file before with OpenSSL : "openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048" # ssl_dhparam /etc/nginx/ssl/dhparam.pem; # Your domain names here server_name www.MY_SITE.com MY_SITE.com 195.xxx.xxx.xxx; index index.php index.html index.htm; root /var/www/MY_SITE.com/public_html; # Your admin folder set $admin_dir /admin274fjp1q; # Gzip Settings, convert all types. gzip on; gzip_vary on; gzip_proxied any; # Can be enhance to 5, but it can slow you server # gzip_comp_level 5; # gzip_min_length 256; gzip_types application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy; # Supposed to be the case but we never know # text/html; # Global rewrite not depending on languages rewrite ^/api/?(.*)$ /webservice/dispatcher.php?url=$1 last; rewrite "^/c/([0-9]+)(\-[_a-zA-Z0-9-]*)/(.*)\.jpg$" /img/c/$1$2.jpg last; rewrite "^/c/([_a-zA-Z-]+)/(.*)\.jpg$" /img/c/$1.jpg last; rewrite "^/([a-z0-9]+)\-([a-z0-9]+)(\-[_a-zA-Z0-9-]*)/(\P{M}\p{M}*)*\.jpg$" /img/p/$1-$2$3.jpg last; rewrite "^/([0-9]+)\-([0-9]+)/(\P{M}\p{M}*)*\.jpg$" /img/p/$1-$2.jpg last; rewrite "^/([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$1$2.jpg last; rewrite "^/([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$1$2$3.jpg last; rewrite "^/([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$1$2$3$4.jpg last; rewrite "^/([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$1$2$3$4$5.jpg last; rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6.jpg last; rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7.jpg last; rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8.jpg last; rewrite "^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?/(\P{M}\p{M}*)*\.jpg$" /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9.jpg last; gzip_disable "MSIE [1-6]\.(?!.*SV1)"; # Symfony controllers location ~ /(AdminDashboard|international|_profiler|module|product|feature|attribute|supplier|combination|specific-price|configure)/(.*)$ { try_files $uri $uri/ /index.php?q=$uri&$args $admin_dir/index.php$is_args$args; } # Redirect needed to "hide" index.php location / { #try_files $uri $uri/ /index.php$uri&$args; try_files $uri $uri/ /index.php?$args; # Old image system ? rewrite ^/([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$1$2$3.jpg last; rewrite ^/([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$1$2$3$4.jpg last; rewrite ^/([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$1$2$3$4$5.jpg last; rewrite ^/([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg last; rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg last; rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg last; rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg last; rewrite ^/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+.jpg$ /img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg$ rewrite ^/c/([0-9]+)(-[.*_a-zA-Z0-9-]*)(-[0-9]+)?/.+.jpg$ /img/c/$1$2$3.jpg last; rewrite ^/c/([a-zA-Z_-]+)(-[0-9]+)?/.+.jpg$ /img/c/$1$2.jpg last; } error_page 404 /index.php?controller=404; # Static assets delivery optimisations add_header Strict-Transport-Security max-age=31536000; # Cloudflare / Max CDN fix location ~* \.(eot|otf|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; } location ~* \.(css|js|docx|zip|pptx|swf|txt|jpg|jpeg|png|gif|swf|webp|flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac)$ { expires max; log_not_found off; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } # Deny access to .htaccess .DS_Store .htpasswd etc location ~ /\. { deny all; } # PHP 7 FPM part location ~ [^/]\.php(/|$) { fastcgi_index index.php; # Switch if needed include /etc/nginx/fastcgi_params; #include fcgi.conf; # Do not forget to update this part if needed fastcgi_pass 127.0.0.1:9000; #fastcgi_pass unix:/run/php/php7.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_keep_conn on; fastcgi_read_timeout 300s; fastcgi_send_timeout 300s; # In case of long loading or 502 / 504 errors # fastcgi_buffer_size 256k; # fastcgi_buffers 256 16k; # fastcgi_busy_buffers_size 256k; client_max_body_size 10M; # Temp file tweak fastcgi_max_temp_file_size 0; fastcgi_temp_file_write_size 256k; } # Allow access to robots.txt but disable logging every access location = /robots.txt { allow all; log_not_found off; access_log off; } # Prevent injection of php files in directories a user can upload stuff location /upload { location ~ \.php$ { deny all; } } location /img { location ~ \.php$ { deny all;} } # Ban access to source code directories location ~ ^/(app|bin|cache|classes|config|controllers|docs|localization|override|src|tests|tools|translations|travis-scripts|vendor)/ { deny all; } # Banned file types location ~ \.(htaccess|yml|log|twig|sass|git|tpl)$ { deny all; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/MY_SITE.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/MY_SITE.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.MY_SITE.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = MY_SITE.com) { return 301 https://$host$request_uri; } # managed by Certbot server_name www.MY_SITE.com MY_SITE.com; listen 80; return 404; # managed by Certbot } 的列。

我要连接到另一个包含3列的表:

PropertyID1

查询在PropertyID, SalePrice, SaleDate PropertyID1上联接,我要获取的是匹配PropertyID的最新迭代,因为每个ID可以有10个以上的匹配项,而我仅需要最新记录,列PropertyID用于选择所需的记录。

所以最初的查询是

SaleDate

返回哪个

CREATE TABLE ##RPP_CHECK
(
     ID INT IDENTITY(1,1) PRIMARY KEY,
     PropertyID1 VARCHAR(255) NULL
);

INSERT INTO ##IDCHECK
VALUES (41572498), (41484495), (41590235), (41611406)

SELECT 
    ID, ##IDCHECK.PropertyID1, PropertyID, SalePrice, SaleDate 
FROM 
    ##IDCHECK
LEFT JOIN 
    [ODS].[RS1] ON [ODS].[RS1].[PropertyID] = ##IDCHECK.PropertyID1 
ORDER BY 
    ID

我需要它退货的是

ID  PropertyID1 PropertyID  SalePrice   SaleDate
--------------------------------------------------
1   41572498    41572498    0.0      01-01-2011
1   41572498    41572498    0.0      01-01-2012
1   41572498    41572498    1000     01-01-2018
2   41484495    41484495    1200     01-02-2018
3   41590235    41590235    2000     01-03-2018
3   41590235    41590235    0.0      01-01-1999
4   41611406    41611406    5000     01-10-2018

我尝试查看此处发布的一些答案,但它们似乎不太合适,我敢肯定这是一个ID PropertyID1 PropertyID SalePrice SaleDate ------------------------------------------------ 1 41572498 41572498 1000 01-01-2018 2 41484495 41484495 1200 01-02-2018 3 41590235 41590235 2000 01-03-2018 4 41611406 41611406 5000 01-10-2018 问题,还是一个分组,但不是100%肯定如此高兴您可以提供的任何提示。

欢呼

3 个答案:

答案 0 :(得分:1)

一个选项使用ROW_NUMBER

SELECT ID, PropertyID1, PropertyID, SalePrice, SaleDate
FROM
(
    SELECT ID, t1.PropertyID1, PropertyID, SalePrice, SaleDate,
        ROW_NUMBER() OVER (PARTITION BY PropertyID ORDER BY SaleDate DESC) rn
    FROM IDCHECK t1
    LEFT JOIN [ODS].[RS1] t2
        ON t2.PropertyID = t1.PropertyID1
) t
WHERE rn = 1;

答案 1 :(得分:1)

APPLY通常具有最佳性能:

SELECT ic.*, r.*
FROM ##IDCHECK ic OUTER APPLY
     (SELECT TOP (1) r.*
      FROM [ODS].[RS1] r
      WHERE r.[PropertyID] = ic.PropertyID1     
      ORDER BY r.SaleDate DESC
     ) r;

答案 2 :(得分:0)

  Use MAX built in function and GROUPBY built in function in JOIN and achieve your 
  result  



BEGIN TRAN
CREATE TABLE #Test ( ID INT ,   PropertyID1 VARCHAR(100) ,  PropertyID 
    VARCHAR(100) ,  SalePrice DECIMAL(12,2) , SaleDate DATETIME )

INSERT INTO #Test ( ID  ,   PropertyID1  ,  PropertyID  ,  SalePrice  , SaleDate)
SELECT 1,'41572498','41572498',0.0,CONVERT(DATETIME,'01-01-2011',103) UNION ALL
SELECT 1,'41572498','41572498',0.0,CONVERT(DATETIME,'01-01-2012',103) UNION ALL
SELECT 1,'41572498','41572498',1000,CONVERT(DATETIME,'01-01-2018',103) UNION ALL
SELECT 2,'41484495','41484495',1200,CONVERT(DATETIME,'01-02-2018',103) UNION ALL
SELECT 3,'41590235','41590235',2000,CONVERT(DATETIME,'01-03-2018',103) UNION ALL
SELECT 3,'41590235','41590235',0.0,CONVERT(DATETIME,'01-01-1999',103) UNION ALL
SELECT 4,'41611406','41611406',5000,CONVERT(DATETIME,'01-10-2018',103)

SELECT ID  ,  PropertyID1  ,  PropertyID  ,  SalePrice  , SaleDate
FROM #Test
JOIN
(
    SELECT PropertyID _PropertyID , PropertyID1 _PropertyID1 , MAX(SaleDate) 
    _SaleDate
   FROM #Test
   GROUP BY PropertyID,PropertyID1
) A ON _SaleDate = SaleDate

ROLLBACK  TRAN