2016-08-11 62 views
0

我已經搜索了這個答案,但還沒有找到一個合適的解決方案。我有一個表'數據'的數據庫,其中我列出了所有產品的過期日期。不同產品的總數大約在120左右,但「數據」表有5000多行。每種產品都有多個單獨的到期監控單位。如何計算多個日期之間的出現次數並僅列出MySQL中的唯一行?

我將需要列出所有具有列的所有獨特產品,以確定每年發生的過期日期。目前,我在主查詢迭代中每年運行多個其他查詢來計算兩個日期之間到期日期的發生次數。

CREATE TABLE IF NOT EXISTS `data` (
`EXPIRY` date DEFAULT NULL, 
`RNO` int(6) DEFAULT NULL, 
`PRODID` int(3) DEFAULT NULL, 
`NAME` varchar(38) DEFAULT NULL, 
`RND` varchar(2) DEFAULT NULL, 
`RDY` varchar(3) DEFAULT NULL, 
`ARTY` varchar(3) DEFAULT NULL, 
`ARYK` varchar(4) DEFAULT NULL, 
`BATCH` varchar(16) DEFAULT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8; 

// list all unique product rows 
$main_loop = $database->query('SELECT * FROM data GROUP BY rno HAVING COUNT(*) >=1'); 
$rows = $database->resultset($main_loop); 
foreach($rows as $data) { 
    echo "<tr>"; 
    echo "<td>".$data['RNO']."</td>"; 
    <td> 
    // another query to count occurrences of expiry in each product between two dates 
    $thisrno = $data['RNO']; 
    $database->query("SELECT * FROM data WHERE EXP BETWEEN '2016-01-01' AND '2016-12-31' AND RNO = '$thisrno'"); 
    $database->execute(); 
    $rows = $database->rowCount(); 
    echo $rows; 
    echo "</td><td>"; 
    ...i would need to do this for each column (2016-2025) 
    ... 
} 

我相信有更好的解決方案。問題在於,這種方式我無法按每年到期單位的數量對錶格進行排序,而且效率不高。

結果應該是這樣的:

RNO | NAME  | Expiring in 2016 | Expiring in 2017 | ... 
336540 | Prod_name_1 | 34    | 62    | 
391755 | Prod_name_2 | 2    | 116    | 
653112 | Prod_name_3 | 46    | 7    | 

回答

0

似乎相當簡單:

select rno, name, 
    sum(exp between '2016-01-01' and '2016-12-31') as exp2016, 
    sum(exp between '2017-01-01' and '2017-12-31') as exp2017, 
    sum(exp between '2018-01-01' and '2018-12-31') as exp2018, 
    sum(exp between '2019-01-01' and '2019-12-31') as exp2019, 
    sum(exp between '2020-01-01' and '2020-12-31') as exp2020, 
    sum(exp between '2021-01-01' and '2021-12-31') as exp2021, 
    sum(exp between '2022-01-01' and '2022-12-31') as exp2022, 
    sum(exp between '2023-01-01' and '2023-12-31') as exp2023, 
    sum(exp between '2024-01-01' and '2024-12-31') as exp2024, 
    sum(exp between '2025-01-01' and '2025-12-31') as exp2025 
from data 
where exp between '2016-01-01' and '2025-12-31' 
group by rno; 

如果你想包括在那些年裏沒有過期甚至產品,省略where子句。

我不確定你的問題是關於排序的問題;你可以選擇一年,並根據當年的到期次數排序行,但這似乎有點奇怪。

+0

非常感謝,我完全忘了sum() - 函數..這是它。 – Sisuman

相關問題