获取至少具有最低数据点的所有资金

时间:2014-07-05 06:11:00

标签: sql-server tsql subquery

我有两张桌子

1)基金详情

ID    Symbol
-------------------
1     ABC
2     XYZ

2)基金价格数据

Fund_id    date                       Price
-------------------------------------------
1          2014-07-01 00:00:00.000    25.25
1          2014-07-02 00:00:00.000    25.45
......
2          2014-07-01 00:00:00.000    75.25
2          2014-07-02 00:00:00.000    75.42
.......

现在我想要实现的是:

我在这里获取特定基金的月度数据如下:

SELECT YEAR(date) [Year], MONTH(date) [Month], 
DATENAME(MONTH,date) [Month Name], COUNT(1) [Sales Count], F.Symbol 
FROM FundData FD inner join FundDetails F on F.ID = FD.Fund_ID 
where F.Symbol = 'ABC' 
GROUP BY YEAR(date), MONTH(date), DATENAME(MONTH, date), F.Symbol

输出:

Year    Month Month Name    Sales Count Symbol
-------------------------------------------
2014    4     April         21          ABC
2014    5     May           21          ABC
2014    6     June          21          ABC
2014    7     July          3           ABC
.......

Total Rows: 301

所以这里仅适用于已返回301行的特定基金。

现在我想从基金详细信息表中获得所有资金,其中行数小于给定的数ex 216,我将作为参数传递

2 个答案:

答案 0 :(得分:0)

使用以下查询:

Declare @YourParameter int = 10

SELECT  YEAR(date) [Year], 
        MONTH(date) [Month], 
        DATENAME(MONTH,date) [Month Name], 
        COUNT(1) [Sales Count], 
        F.Symbol 
FROM FundData FD 
INNER JOIN FundDetails F on FD.ID = F.Fund_ID
Where FD.ID IN (SELECT z.Fund_ID
                 FROM FundDetails z
                 WHERE z.Fund_ID=FD.ID
                 GROUP BY z.Fund_ID, YEAR(z.date), MONTH(z.date)
                 HAVING COUNT(*) <= @YourParameter
                 )
GROUP BY YEAR(date), MONTH(date), DATENAME(MONTH, date), F.Symbol

答案 1 :(得分:0)

我修好了它:

Declare @YourParameter int = 110

WITH CTE AS
(
    SELECT YEAR(date) [Year], MONTH(date) [Month], 
    DATENAME(MONTH,date) [Month Name], COUNT(1) [Sales Count], F.Symbol 
    FROM FundData FD inner join FundDetails F on F.ID = FD.Fund_ID 
    where F.ID 
    IN (SELECT z.ID FROM FundDetails z)
    GROUP BY F.Symbol, YEAR(date), MONTH(date), DATENAME(MONTH, date)
)
SELECT Symbol, COUNT(*) as cnt FROM CTE
GROUP BY Symbol
having COUNT(*) >= @YourParameter