我正在将一个项目从MySQL迁移到MSSQL。而且由于我在Mssql方面非标准使用分组,所以无法显示正确的数据。我需要一个建议。
SELECT Count(*) AS stok_adet, s.*, m.*,d.*
FROM stok AS s
CROSS JOIN mermer_cins AS m
JOIN stok_durum AS d
ON s.stok_durum_id = d.stok_durum_id
WHERE m.mermer_cins_id = '5'
AND s.blok_no = 'M6320'
GROUP BY s.bundle_no,
s.boy,
s.yukseklik,
s.hatali
ORDER BY s.blok_no ASC,
s.bundle_no ASC,
s.stok_tarih DESC
Mysql结果ss:https://i.ibb.co/ssknfwM/mysql.png
我在Mssql端尝试了两种不同的方法。
SELECT COUNT(*) as stok_adet,
s.bundle_no, s.boy, s.yukseklik, s.hatali
FROM stok s CROSS JOIN
mermer_cins m JOIN
stok_durum d
ON s.stok_durum_id = d.stok_durum_id
WHERE m.mermer_cins_id = '5' AND s.blok_no = 'M6320'
GROUP BY s.bundle_no, s.boy, s.yukseklik, s.hatali;
Mssql第一个结果ss:https://i.ibb.co/d5wxcD7/mssql-first.png
SELECT s.*, m.*,
(SELECT COUNT(*)
FROM stok_durum d
WHERE s.stok_durum_id = d.stok_durum_id
) as stok_adet
FROM stok s CROSS JOIN
mermer_cins m
WHERE m.mermer_cins_id='5' AND s.blok_no='M6320'
ORDER BY s.blok_no ASC, s.bundle_no ASC, s.stok_tarih DESC
Mssql第二个结果ss:https://i.ibb.co/cY2cvMS/mssql-second.png
答案 0 :(得分:0)
还有另一种选择:
SELECT sm.*,
(SELECT COUNT(*)
FROM stok_durum d
WHERE sm.stok_durum_id = sm.stok_durum_id
) as stok_adet
FROM (SELECT s.*, m.*,
ROW_NUMBER() OVER (PARTITION BY s.bundle_no, s.boy, s.yukseklik, s.hatali
ORDER BY (SELECT NULL)
) as seqnum
FROM stok s CROSS JOIN
mermer_cins m
WHERE m.mermer_cins_id = '5' AND s.blok_no = 'M6320'
) sm
WHERE sequm = 1
ORDER BY sm.blok_no ASC, sm.bundle_no ASC, sm.stok_tarih DESC
子查询使用窗口函数来选择任意匹配的行。