[英]How to group rows in SQL by earliest date when are there are multiple rows with earliest date?
[英]sql select earliest date for multiple rows
我有一個如下所示的數據庫;
circuit_uid | customer_name | location | reading_date | reading_time | amps | volts | kw | kwh | kva | pf | key
--------------------------------------------------------------------------------------------------------------------------------------
cu1.cb1.r1 | Customer 1 | 12.01.a1 | 2012-01-02 | 00:01:01 | 4.51 | 229.32 | 1.03 | 87 | 1.03 | 0.85 | 15
cu1.cb1.r1 | Customer 1 | 12.01.a1 | 2012-01-02 | 01:01:01 | 4.18 | 230.3 | 0.96 | 90 | 0.96 | 0.84 | 16
cu1.cb1.s2 | Customer 2 | 10.01.a1 | 2012-01-02 | 00:01:01 | 7.34 | 228.14 | 1.67 | 179 | 1.67 | 0.88 | 24009
cu1.cb1.s2 | Customer 2 | 10.01.a1 | 2012-01-02 | 01:01:01 | 9.07 | 228.4 | 2.07 | 182 | 2.07 | 0.85 | 24010
cu1.cb1.r1 | Customer 3 | 01.01.a1 | 2012-01-02 | 00:01:01 | 7.32 | 229.01 | 1.68 | 223 | 1.68 | 0.89 | 48003
cu1.cb1.r1 | Customer 3 | 01.01.a1 | 2012-01-02 | 01:01:01 | 6.61 | 228.29 | 1.51 | 226 | 1.51 | 0.88 | 48004
我想要做的是產生一個結果,該結果具有從該日起最早( min(reading_time)
)的每個客戶的KWH讀數,該日期將由用戶在Web表單中選擇。
結果將是/應該類似於;
Customer 1 87
Customer 2 179
Customer 3 223
這里顯示的每天行數超過了客戶數量,客戶數量也會增加,客戶數量也會定期變化。
我沒有太多的SQL經驗,我已經查看了子查詢等但我沒有找到如何根據每個客戶的最早讀數排列它然后只輸出kwh
列。
這是在Redhat / CentOS上的PostgreSQL 8.4中運行的。
select customer_name,
kwh,
reading_date,
reading_time
from (
select customer_name,
kwh,
reading_time,
reading_date,
row_number() over (partition by customer_name order by reading_time) as rn
from readings
where reading_date = date '2012-11-17'
) t
where rn = 1
作為備選:
select r1.customer_name,
r1.kwh,
r1.reading_date,
r1.reading_time
from readings r1
where reading_date = date '2012-11-17'
and reading_time = (select min(r2.reading_time)
from readings
where r2.customer_name = r1.customer_name
and r2.read_date = r1.reading_date);
但我希望第一個更快。
順便說一句:為什么要將日期和時間存儲在兩個單獨的列中? 您是否意識到使用timestamp
列可以更好地處理這個問題?
這應該是最快的解決方案之一:
SELECT DISTINCT ON (customer_name)
customer_name, kwh -- add more columns as needed.
FROM readings
WHERE reading_date = user_date
ORDER BY customer_name, reading_time
似乎是另一個應用:
SELECT rt.circuit_uid , rt.customer_name, rt.kwh
FROM READING_TABLE rt JOIN
(SELECT circuit_uid, reading_time
FROM READING_TABLE
WHERE reading_date = '2012-01-02'
GROUP BY customer_uid
HAVING MIN(reading_time) = reading_time) min_time
ON (rt.circuit_uid = min_time.circuit_uid
AND rt.reading_time = min_time.reading_time);
參數化上面查詢中的reading_date值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.