我在Web表单中继承了一个代码库,并且遇到了SQL查询的问题。
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC
在表格service_fakturering
中,有多个行具有相同的service_id
我需要选择要在INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
答案 0 :(得分:2)
使用ROW_NUMBER()
功能以及common table expression,可以这样做:
WITH cte_service_fakturering AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY service_id ORDER BY id DESC) RN
FROM service_fakturering
)
SELECT foretag.namn, foretag.epost, foretag.forlangEj, cte.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN cte_service_fakturering cte ON service.id = cte.service_id AND cte.RN = 1
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC
答案 1 :(得分:1)
Sub select会将service_fakturering行分组并为您获取maxId。然后,它将用于连接回您的查询并仅过滤您感兴趣的行。
SELECT foretag.namn, foretag.epost, foretag.forlangEj, service_fakturering.*
FROM foretag
INNER JOIN service ON foretag.id = service.foretagsid
INNER JOIN service_fakturering ON service.id = service_fakturering.service_id
INNER JOIN (Select service_fakturering.service_id, Max(service_fakturering.id) as Id
FROM service_fakturering
GROUP BY service_fakturering.service_id) x
ON x.service_id = service_fakturering.service_id
AND x.Id = service_fakturering.Id
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC, id DESC
答案 2 :(得分:1)
试试这个......
您可以使用ROW_NUMBER
来表示集合的订单
WITH CTE
AS (
SELECT *
, ROW_NUMBER() OVER (
PARTITION BY service_id ORDER BY ID DESC
) ROWNUM
FROM service_fakturering
)
SELECT foretag.namn
, foretag.epost
, foretag.forlangEj
, service_fakturering.*
FROM foretag
INNER JOIN service
ON foretag.id = service.foretagsid
INNER JOIN service_fakturering
ON service.id = service_fakturering.service_id
AND ROW_NUM = 1
WHERE service_fakturering.giltighets_datum <= DATEADD(D, 30, GETDATE())
ORDER BY bestallnings_datum DESC
, id DESC