SQL值重复

时间:2017-08-11 12:42:08

标签: sql sql-server-2012

全部,

这可能很容易,但我需要一些帮助。

我目前有一个返回这些结果的查询:

Transaction ID | Date     | Product Code | Tranaction Type | Customer ID
-------------- | ---------| ------------ | --------------- | -----------
1              | 20170810 | X1           | T               | 1000 0000 0000 0001
1              | 20170810 | X2           | I               |
1              | 20170810 | X3           | I               |

我想知道如何在每条交易行上添加客户ID?

请参阅下面我当前的查询

SELECT 
DAILYSALES.INTTRANSNUM AS [TRANSACTION ID],
Convert(CHAR(8), DTMSALEDATETIME, 112) AS [DATE], 
dbo.DAILYSALES.LINTITEMNUMBER AS [PRODUCT CODE], 
DAILYSALES.STRCOMMENT AS [CUSTOMER ID]

FROM dbo.DAILYSALES (NOLOCK)
LEFT JOIN ITEM (NOLOCK) ON DAILYSALES.LINTITEMNUMBER = ITEM.LINTITEMNUMBER


WHERE 
(DAILYSALES.DTMTRADEDATE >= GETDATE()-2 AND DRSDATA.dbo.DAILYSALES.DTMTRADEDATE <= GETDATE())
AND (STRSALETYPE IN ('I','T'))

任何帮助将不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:2)

您可以使用窗口功能:

SELECT ds.INTTRANSNUM AS [TRANSACTION ID],
       Convert(CHAR(8), DTMSALEDATETIME, 112) AS [DATE], 
       ds.LINTITEMNUMBER AS [PRODUCT CODE], 
       ds.STRCOMMENT AS [CUSTOMER ID],
       MAX(ds.STRCOMMENT) OVER (PARTITION BY ds.INTTRANSNUM) as customer_id
FROM dbo.DAILYSALES ds LEFT JOIN
     ITEM i 
     ON ds.LINTITEMNUMBER = i.LINTITEMNUMBER
WHERE ds.DTMTRADEDATE >= GETDATE() - 2 AND 
      ds.DTMTRADEDATE <= GETDATE() AND
      STRSALETYPE IN ('I', 'T');