我希望在SQL Server 2014中运行SQL,这将使我获得表中多于一行的项目(INV_ITEM_ID
),和具有相同的生效日期( EFFDT
),如下例所示。
SETID INV_ITEM_ID VENDOR_SETID VENDOR_ID UNIT_OF_MEASURE EFFDT
-----------------------------------------------------------------------------------------
SHARE 1 SHARE ERSUT BX 2018-07-16 00:00:00.000
SHARE 1 SHARE ERSUT BX 2018-09-01 00:00:00.000
SHARE 10 SHARE ERSUT RL 1901-01-01 00:00:00.000
SHARE 100 SHARE JJHS CS 1901-01-01 00:00:00.000
SHARE 100 SHARE PSMED CS 1901-01-01 00:00:00.000
上述输出中的项目100将是一个很好的例子,该项目多次出现并且两行具有相同的EFFDT(1901-01-01)。
这是我尝试过的SQL,但是没有给我预期的输出:
SELECT
SETID, INV_ITEM_ID, VENDOR_SETID, VENDOR_ID, UNIT_OF_MEASURE, EFFDT
FROM
PS_ITM_VNDR_UOM_PR A
WHERE
EXISTS (SELECT 1 FROM PS_ITM_VNDR_UOM_PR B
WHERE B.INV_ITEM_ID = A.INV_ITEM_ID AND B.EFFDT = A.EFFDT)
GROUP BY
SETID, INV_ITEM_ID, VENDOR_SETID, VENDOR_ID, UNIT_OF_MEASURE, EFFDT
HAVING
COUNT(INV_ITEM_ID) > 1 AND COUNT(EFFDT) > 1
ORDER BY
INV_ITEM_ID
答案 0 :(得分:1)
SELECT
*
FROM
TABLENAME a
WHERE EXISTS
(SELECT
COUNT(1) cnt
,inv_item_id
,effdt
FROM
TABLENAME b
WHERE b.inv_item_id = a.inv_item_id
GROUP BY inv_item_id,effdt
HAVING COUNT(1) > 1)
答案 1 :(得分:0)
以下查询应会得到您想要的:
with x as (
select inv_item_id, effdt
from ps_itm_vndr_uom_pr
group by inv_item_id, effdt
having count(*) > 1
)
select inv_item_id
from x
group by inv_item_id
having count(*) = 1
答案 2 :(得分:0)
您要选择INV_ITEM_ID
和EFFDT
> 1的行数的所有行。使用COUNT OVER
可以轻松解决:
select setid, inv_item_id, vendor_setid, vendor_id, unit_of_measure, effdt
from
(
select *, count(*) over (partition by inv_item_id, effdt) as cnt
from ps_itm_vndr_uom_pr
) t
where cnt > 1
order by inv_item_id, effdt;