帮忙看一下这个sql怎么写才好.
g_trade_tradelist 是订单表
g_trade_goodslist 是物品明细表
两个表之间tradeid字段是关联的.
tradelist中tradestatus=5 and printexpress=''之外的单是不查询的.
现在想查询在g_trade_goodslist中出现次数最多的货品(货品列名是'goodsid')在g_trade_tradelist中对应的所有订单(满足tradestatus=5 and printexpress=''两个条件的)
我用的是
select * FROM [wdgj30].[dbo].[G_Trade_GoodsList] where TradeID in(
select TradeID from (
select top 1 goodsid,count(GoodsID)as c from wdgj30.dbo.G_Trade_GoodsList where TradeID in(
select tradeid from wdgj30.dbo.g_trade_tradelist where tradestatus=5 and printexpress=''
)group by GoodsID order by c desc
)a
)
select TradeID from (
select top 1 goodsid,count(GoodsID)as c
SELECT *
FROM g_trade_tradelist a
WHERE EXISTS ( SELECT 1
FROM ( SELECT TOP 1
tradeid ,
COUNT(1) c
FROM g_trade_goodslist
GROUP BY tradeid
ORDER BY COUNT(1)
) b
WHERE a.tradeid = b.tradeid )
AND tradestatus = 5
AND printexpress = ''
select * from #g_trade_tradelist where TradeID in
(
---取符合条件的TradeID
select c.TradeID from #g_trade_tradelist c
join #g_trade_goodslist d on c.TradeID=d.TradeID
and c.tradestatus=5 and c.printexpress=''-----加上限制
and d.goodsid in
(
--分组,降序排列,取第一个goodsId
select top 1 goodsid from
(
---查询#g_trade_tradelist中符合tradestatus=5 and printexpress='' 的记录
select a.TradeID,b.goodsid
from #g_trade_tradelist a
join #g_trade_goodslist b
on a.TradeID=b.TradeID and a.tradestatus=5 and a.printexpress=''----这里实际上已经加过限制了
) t group by goodsid order by count(goodsid) desc
)
)