由于日期值不同,如何防止以下查询中出现多个相同的价格行?我只需要显示价格与先前记录不同的记录的第一次出现,但是跳过直到价格字段发生另一次更改。
SELECT STOCKID, PRICE, TRANSTYPENAME, TRANSDATE
FROM VE_STOCKTRANS
WHERE STOCKID = 6000 AND TANSTYPE IN (3500,3553)
GROUP BY PRICE, STOCKID, TRANSTYPENAME, TRANSDATE
即我需要省略多个35.83333333行,而仅采用它的首次出现(24/4/2018)
对戈登答案的图片答复:
答案 0 :(得分:0)
使用LAG()
查看价格是否发生变化:
SELECT STOCKID, PRICE, TRANSTYPENAME, TRANSDATE
FROM (SELECT st.*,
LAG(st.price) OVER (PARTITION BY stockId ORDER BY transdate) as prev_price
FROM VE_STOCKTRANS st
WHERE STOCKID = 6000 AND TANSTYPE IN (3500, 3553)
) st
WHERE prev_price IS NULL OR prev_price <> price;
编辑:
如果您只希望第一次看到每个价格的列表(与您在问题中提到并描述的价格变化大不相同),请使用row_number()
:
SELECT STOCKID, PRICE, TRANSTYPENAME, TRANSDATE
FROM (SELECT st.*,
ROW_NUMBER() OVER (PARTITION BY st.stockId, st.price ORDER BY st.transdate) as seqnum
FROM VE_STOCKTRANS st
WHERE STOCKID = 6000 AND TANSTYPE IN (3500, 3553)
) st
WHERE seqnum = 1;
答案 1 :(得分:0)
您可以这样获得第一个TRANSDATE:
SELECT STOCKID, PRICE, TRANSTYPENAME, min(TRANSDATE)
FROM VE_STOCKTRANS
WHERE STOCKID = 6000 AND TRANSTYPE IN (3500,3553)
GROUP BY PRICE, STOCKID, TRANSTYPENAME
答案 2 :(得分:0)
glm()
这可能会有帮助。