根据您的子查询,您似乎可以在没有相关子查询的情况下解决您的问题,并且只能使用连接。然而,只有一部分查询可以使用,所以很难确定。这就是为什么在发布问题时最好发布尽可能多的相关代码。尽管如此,据我所知,你有这样的事情:
SELECT ( SELECT SUM(chh2.cha_meblag)
FROM dbo.CARI_HESAP_HAREKETLERI chh2
WHERE chh2.cha_normal_Iade = 1
AND chh2.cha_kod = ch.cari_kod
AND chh2.cha_tarihi >= '20130101'
AND chh2.cha_tarihi <= '20130131'
) AS Ocai,
( SELECT SUM(chh2.cha_meblag)
FROM dbo.CARI_HESAP_HAREKETLERI chh2
WHERE chh2.cha_normal_Iade = 1
AND chh2.cha_kod = ch.cari_kod
AND chh2.cha_tarihi >= '20130201'
AND chh2.cha_tarihi <= '20130228'
) AS Ocai,
... etc for 12 months
FROM SomeTable ch
你可以把它变成:
SELECT ch.cari_kod,
[20130101] = ISNULL([20130101], 0),
[20130201] = ISNULL([20130201], 0),
[20130301] = ISNULL([20130301], 0),
[20130401] = ISNULL([20130401], 0),
[20130501] = ISNULL([20130501], 0),
[20130601] = ISNULL([20130601], 0),
[20130701] = ISNULL([20130701], 0),
[20130801] = ISNULL([20130801], 0),
[20130901] = ISNULL([20130901], 0),
[20131001] = ISNULL([20131001], 0),
[20131101] = ISNULL([20131101], 0),
[20131201] = ISNULL([20131201], 0)
FROM SomeTable
LEFT JOIN
( SELECT chh2.cha_kod,
[20130101] = SUM(CASE WHEN chh2.cha_tarihi >= '20130101' AND chh2.cha_tarihi < '20130201' THEN chh2.cha_meblag ELSE 0 END),
[20130201] = SUM(CASE WHEN chh2.cha_tarihi >= '20130201' AND chh2.cha_tarihi < '20130301' THEN chh2.cha_meblag ELSE 0 END),
[20130301] = SUM(CASE WHEN chh2.cha_tarihi >= '20130301' AND chh2.cha_tarihi < '20130401' THEN chh2.cha_meblag ELSE 0 END),
[20130401] = SUM(CASE WHEN chh2.cha_tarihi >= '20130401' AND chh2.cha_tarihi < '20130501' THEN chh2.cha_meblag ELSE 0 END),
[20130501] = SUM(CASE WHEN chh2.cha_tarihi >= '20130501' AND chh2.cha_tarihi < '20130601' THEN chh2.cha_meblag ELSE 0 END),
[20130601] = SUM(CASE WHEN chh2.cha_tarihi >= '20130601' AND chh2.cha_tarihi < '20130701' THEN chh2.cha_meblag ELSE 0 END),
[20130701] = SUM(CASE WHEN chh2.cha_tarihi >= '20130701' AND chh2.cha_tarihi < '20130801' THEN chh2.cha_meblag ELSE 0 END),
[20130801] = SUM(CASE WHEN chh2.cha_tarihi >= '20130801' AND chh2.cha_tarihi < '20130901' THEN chh2.cha_meblag ELSE 0 END),
[20130901] = SUM(CASE WHEN chh2.cha_tarihi >= '20130901' AND chh2.cha_tarihi < '20131001' THEN chh2.cha_meblag ELSE 0 END),
[20131001] = SUM(CASE WHEN chh2.cha_tarihi >= '20131001' AND chh2.cha_tarihi < '20131101' THEN chh2.cha_meblag ELSE 0 END),
[20131101] = SUM(CASE WHEN chh2.cha_tarihi >= '20131101' AND chh2.cha_tarihi < '20131201' THEN chh2.cha_meblag ELSE 0 END),
[20131201] = SUM(CASE WHEN chh2.cha_tarihi >= '20131201' AND chh2.cha_tarihi < '20140101' THEN chh2.cha_meblag ELSE 0 END)
FROM dbo.CARI_HESAP_HAREKETLERI chh2
WHERE chh2.cha_normal_Iade = 1
GROUP BY chh2.cha_kod
) chh2
ON chh2.cha_kod = ch.cari_kod;
这甚至可能不需要子查询,但是正如我所说,如果没有您的完整查询,我只能推测您的表结构以及您实际想要的结果。
回答 1 是的,UDF 的性能比执行相同操作的子查询差是正常的。关于这个主题有很多帖子当我搜索SQL-Server UDF 与子查询时,这个答案是谷歌的顶部