SQL Server查询group by子句

时间:2019-01-04 10:53:09

标签: sql sql-server tsql

我写了查询。下面是该查询

SELECT
  COUNT(amount) AS NR_Sales,
  DATEPART(YEAR, crn_dt) AS years
FROM c_Payment_service_fee
WHERE CFK_F_key IN (SELECT
  FK_2290F_key
FROM C_Submissions
WHERE FK_C_UP_key IN (SELECT
  PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND amount > 0
GROUP BY DATEPART(YEAR, crn_dt)

还有一个

SELECT
  amount AS NR_Sales,
  DATEPART(YEAR, crn_dt) AS years
FROM c_Payment_service_fee
WHERE CFK_F_key IN (SELECT
  FK_2290F_key
FROM C_Submissions
WHERE FK_C_UP_key IN (SELECT
  PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND DATEPART(YEAR, crn_dt) = 2019)
AND DATEPART(YEAR, crn_dt) = 2019
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date)))
AND DATEPART(WEEK, crn_dt) BETWEEN 1 AND (DATEPART(WEEK, @date))
AND amount > 0
AND DATEPART(YEAR, crn_dt) = 2019

两者都工作正常,没有错误。但是我的问题是,如果我第一次运行查询2019,则计数为303,如果运行第二次查询269,则显示的是2019年的数据。

在我犯错误的地方,我找不到问题,请帮我解决这个问题。

3 个答案:

答案 0 :(得分:3)

SELECT
PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND 
(DATEPART(WEEK, @date))
AND DATEPART(YEAR, crn_dt) = 2019

更具限制性
SELECT
PK_C_UP_key
FROM C_User_Profile
WHERE DATEPART(WEEK, crn_dt) BETWEEN 1 AND 
(DATEPART(WEEK, @date))

因此,FK_C_UP_key可以在您的第一个查询中从子查询中获取更多值。

答案 1 :(得分:0)

选择   COUNT(amount)AS NR_Sales,   DATEPART(YEAR,crn_dt)AS年 从c_Payment_service_fee 按日期分组(年,crn_dt)

答案 2 :(得分:0)

您的第一个查询具有:

SELECT COUNT(amount) AS NR_Sales, DATEPART(YEAR, crn_dt) AS years

您的第二个具有:

SELECT amount AS NR_Sales, DATEPART(YEAR, crn_dt) AS years

您正在将行数与列总数进行比较。我不奇怪他们与众不同。

我不知道您想要什么,但是我建议您在两个查询中都使用它:

SELECT YEAR(crn_dt), COUNT(*) as num_rows,
       SUM(amount) as total_amount