我有许多客户的Microsoft SQL数据库,列是CustomerID,CustomerName,Locations,SQFT,EditDate, DateRecorded
每天,我们都会记录客户使用的面积。因此,数据库应该具有该月每天的值。我想为每位顾客选择面积最高的日子。以下代码仅返回单个客户,而不是所有客户。如何为每位客户返回当月最高的SQFT?
我的代码:
// $db_month_start = the first of the current month.
// $db_month_end = the end of the current month.
$query = "SELECT CustomerID,CustomerName,SQFT,EditDate
FROM SquareFootage
WHERE DateRecorded >= '{$db_month_start}'
AND DateRecorded <= '{$db_month_end}'
AND SQFT = (Select Max(SQFT) From SquareFootage WHERE DateRecorded >= '{$db_month_start}' AND DateRecorded <= '{$db_month_end}') ";
答案 0 :(得分:2)
每位客户每月最高SQFT:
select CustomerID
, CustomerName
, convert(varchar(7), DateRecorded, 120) as [Month]
, max(SQFT) as MaxSQFTThisMonth
from SquareFootage
group by
CustomerID
, CustomerName
, convert(varchar(7), DateRecorded, 120)
这将适用于任意数月,并且多天内拥有最高SQFT的客户仅列在一行中。
答案 1 :(得分:1)
您可以按照相同的路径进行操作。您只需要一个相关的子查询:
SELECT CustomerID, CustomerName, SQFT, EditDate
FROM SquareFootage sf
WHERE DateRecorded >= '{$db_month_start}' AND DateRecorded <= '{$db_month_end}' AND
SQFT = (Select Max(sf2.SQFT)
From SquareFootage sf2
WHERE sf2.DateRecorded >= '{$db_month_start}' AND
sf2.DateRecorded <= '{$db_month_end}' AND
sf2.CustomerId = sf.CustomerId
);
答案 2 :(得分:0)
with cte as (
SELECT *, rank() over (partition by CustomerId order by SQFT desc) as [r]
FROM SquareFootage
WHERE DateRecorded >= '{$db_month_start}'
AND DateRecorded <= '{$db_month_end}'
)
select CustomerID,CustomerName,SQFT,EditDate
from cte
where [r] = 1
此查询显示为“对于每个客户,按SQFT按相反顺序对记录进行排名。然后,返回每个客户的最高记录”。