我有以下SQL查询:
select count(t.id) from Tickets t
where t.IsPaid = 1 and t.Price_id = (select price.Id from Prices price
where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
where price.Product_id = pr.Id)))
问题是:如何从我的代码的这一部分获取具有最小值price.Price1字段的行?
(select price.Id from Prices price
where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
where price.Product_id = pr.Id)))
我希望由于我的代码的第二部分将只是ONE行的Id。现在这个代码总是给我所有的价格。 这是主表Database structure and relations
中的关系我尝试了不同的方法:
(select price.Id, MIN(Price1) from Prices price
where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F' AND price.Quantity > (select count(t1.Id) from Tickets t1
where t1.IsPaid = 1 AND t1.Price_id IN (select pr.Id from Prices pr
where price.Product_id = pr.Id)) Group by Id)
价格表中的数据示例:Prices table
票证表中的数据示例:Tickets table
答案 0 :(得分:1)
我认为你想要实现的目标: 对于给定的产品ID,找到可用的未付票据的最低价格,然后显示可用的票数
如果这是正确的:
SELECT isnull(ticket_count, 0) AS ticket_count
FROM
(
SELECT *
FROM (SELECT Price_Id, MIN(Price1) OVER (Partition By Product_id) min_price from Prices) x
WHERE min_price=Price1
) p
JOIN
(
SELECT COUNT(Id) ticket_count, Price_Id FROM Tickets WHERE IsPaid=1 GROUP BY Price_Id
) t ON p.Price_Id=t.Price_Id
WHERE p.Quantity > t.ticket_count
答案 1 :(得分:0)
问题是:如何获得具有最小价格价值的行。价格1 我这部分代码的字段?
简单:
(select TOP 1 price.Id
from Prices price
where price.Product_id = '7E67DAFB-C819-4715-830A-7C89EC986E4F'
AND price.Quantity > (
select count(t1.Id)
from Tickets t1
where t1.IsPaid = 1
AND t1.Price_id IN (select pr.Id from Prices pr where price.Product_id = pr.Id)
)
ORDER BY price.Price1 ASC
)