2017-04-05 48 views
-1

我有列和 日期格式爲dd/mm/yyyy格式。將SQL查詢分組到硬代碼列

Date   Description. Id.  Amt 
01/01/2000.  ABC.  D1.  100 
02/01/2000.  XYZ.  R1  100 
01/01/2000.  PQR.  D1.  100 
01/02/2000.  CDF.  D1.  150 

現在我需要查詢顯示

Date   Description. Id.  Amt 
01/01/2000.  ABC.  D1. 200 
02/01/2000.  XYZ.  R1  100 
01/02/2000.  CDF.  D1. 150 

我需要按日期和總結的量。但我也需要對我選擇的描述值ABC進行硬編碼。

+0

你的意思是硬編碼描述爲一組?訂單應該是什麼?對於'01/01/2000',amond'ABC'和'PQR',你爲什麼要'ABC'?按字母順序?你也不想用'id'分組嗎?如果不是那麼你應該顯示哪個「id」,如果它們對於一個組是不同的? – Utsav

+0

到目前爲止您嘗試過什麼? – Aleksej

+0

我只想按日期進行分組,而不是按ID進行分組。這不是ABC或PQR當我有相似的日期時,我應該能夠使用自己的硬編碼文本'X0000'。 – MKS

回答

1

您可以使用CASE具有聚合硬編碼說明時組大小是多行:

select the_date, 
    id, 
    case 
     when count(*) > 1 
      then 'ABC' 
     else max(description) 
     end as description, 
    sum(amt) as amt 
from your_table 
group by the_date, 
    id 

另外請注意,我叫datethe_date作爲date是一個保留關鍵詞。所以,避免使用它或使用雙引號將其轉義(我只是使用其他名稱)。

0

我認爲這是你需要根據你的預期產出。但是你可能想要檢查你想要硬編碼的min(description)。也min(id) is assuming that ID is same for same日期. But if it is different, the you have to decide which ID`你想顯示。

select date, 
min(description), --assuming you want it alphabatically. 
min(id), --assuming they are same for a group. If they are different, the dispay alphabatically. 
sum(amt) 
from your_table 
group by date