SQL / Qlikview,返回所有MAX值

时间:2016-10-23 16:47:19

标签: sql sql-server max inner-join qlikview

我正在使用Qlikview构建报告,我发现难以填充特定的表格。

在此表tbl.scores中,我想返回每个名称的最新得分值。在下表中

tbl_scores
Name    Date    Score
James   20160101    82
Simon   20160505    66
Peter   20160404    49
John    20160303    91
Sarah   20160820    68
Joe 20160202    12
James   20160921    43
Simon   20160701    77
Peter   20160319    75
John    20160905    18
Sarah   20160130    39
Joe 20160604    25

我想拥有的是

Name    Score
James   43
Simon   77
Peter   49
John    18
Sarah   68
Joe 25

我找到每个名字的最大日期并返回分数。

目前我不得不将其限制为一个名称,否则SQL不起作用

成绩: SQL

SELECT          
Name,
Score 
FROM       tbl_scores
WHERE
Name = 'James'
AND
Date = (SELECT MAX(Date) FROM tbl_scores WHERE Name = 'James');   

我需要更改什么才能获得所需的结果?

4 个答案:

答案 0 :(得分:3)

如果您想在QlikView而不是SQL中执行此操作(即通过所有分数并在此方案中显示您想要的那些),那么您可以在图表表达式中使用FirstSortedValue。

https://help.qlik.com/en-US/qlikview/12.0/Subsystems/Client/Content/ChartFunctions/BasicAggregationFunctions/firstsortedvalue.htm

答案 1 :(得分:1)

您可以使用ROW_NUMBER窗口功能对所有Name's

执行相同的操作
Select * from 
(
select row_number() over(partition by Name order by [Date] desc),*
From tbl_scores
)A
Where Rn = 1

使用TOP 1 with Ties

的另一种方法
select TOP 1 with Ties *
From tbl_scores
Order by row_number() over(partition by Name order by [Date] desc)

<强>样本

CREATE TABLE tbl_scores
    ([Name] varchar(5), [Date] datetime, [Score] int)
;

INSERT INTO tbl_scores
    ([Name], [Date], [Score])
VALUES
    ('James', '20160101', 82),
    ('Simon', '20160505', 66),
    ('Peter', '20160404', 49),
    ('John',  '20160303', 91),
    ('Sarah', '20160820', 68),
    ('Joe',   '20160202', 12),
    ('James', '20160921', 43),
    ('Simon', '20160701', 77),
    ('Peter', '20160319', 75),
    ('John',  '20160905', 18),
    ('Sarah', '20160130', 39),
    ('Joe',   '20160604', 25)
;

结果:

+-------+-------------------------+-------+
| Name  |          Date           | Score |
+-------+-------------------------+-------+
| James | 2016-09-21 00:00:00.000 |    43 |
| Joe   | 2016-06-04 00:00:00.000 |    25 |
| John  | 2016-09-05 00:00:00.000 |    18 |
| Peter | 2016-04-04 00:00:00.000 |    49 |
| Sarah | 2016-08-20 00:00:00.000 |    68 |
| Simon | 2016-07-01 00:00:00.000 |    77 |
+-------+-------------------------+-------+

答案 2 :(得分:0)

使用JOINS你可以这样做

SELECT t1.name,t1.score
FROM tbl_scores t1
INNER JOIN
(
SELECT name,MAX([Date]) as RecentDate
FROM tbl_scores
GROUP BY name
) t2
ON t1.[Date] = t2.[RecentDate]

答案 3 :(得分:0)

你也可以使用外部申请:

  SELECT f1.name,f3.*
  FROM tbl_scores f1
  outer apply
  (
  SELECT top 1 f2.[Date], t1.score 
  FROM tbl_scores f2
  where f1.Name=f2.name
  order by f2.[Date] desc
  ) t3