我有一张包含此信息的表
ACCTCCODE | ACCTDESCRIPTION | ISSUEDATE
----------+-----------------+----------------
1031 | Blahdescription | 2018-03-11
1032 | Blahdescription | 2017-04-18
1033 | Blahdescription | 2018-04-15
1034 | Blahdescription | 2018-011-04
我想尝试两次获取日期?对于两个单独的列。例如
ACCTCCODE | ACCTDESCRIPTION | FIRSTCOUNT | SECOUNDCOUNT
----------+-----------------+-------------+--------------
1031 | Blahdescription | 150 23
1032 | Blahdescription | 75 101
1033 | Blahdescription | 3 78
1034 | Blahdescription | 11 23
我试图用SELECT内的SELECT创建查询,但是对于sql来说是新手,所以在使其工作方面有些麻烦。
这是我想出的方法,它适用于第一个计数,但不适用于第二个计数。
SELECT DISTINCT
account AS ACCTCODE, Description AS ACCTDESCRIPTION,
COUNT(issueDate) AS FIRSTCOUNT,
(SELECT COUNT(issueDate)
FROM Table1
WHERE issueDate BETWEEN CONVERT(DATETIME, '2018-2-31')
AND CONVERT(DATETIME, '2018-04-03')
AND account <> '') AS SECONDCOUNT
FROM
Table1
WHERE
issueDate BETWEEN CONVERT(DATETIME, '2017-11-31')
AND CONVERT(DATETIME, '2018-02-01')
AND account <> ''
GROUP BY
account, Description
ORDER BY
account, Description ASC
答案 0 :(得分:1)
每个日期间隔一次将SUM()与CASE一起使用
SELECT account AS ACCTCODE, description AS ACCTDESCRIPTION,
SUM(CASE WHEN issuedate BETWEEN CONVERT(DATE, '20171131', 112) AND CONVERT(DATE, '20180201', 112)
THEN 1 ELSE 0 END) as FIRSTCOUNT,
SUM(CASE WHEN issuedate BETWEEN CONVERT(DATE, '20180228', 112) AND CONVERT(DATE, '20180403', 112)
THEN 1 ELSE 0 END) as SECONDCOUNT
FROM Table1
GROUP BY account, description
答案 1 :(得分:0)
您可以通过以下情况来尝试以下操作
select ACCTCCODE,ACCTDESCRIPTION ,sum(case when issueDate>='2017-11-31' and issueDate<='2018-02-01' then 1 else 0 end)
as FIRSTCOUNT ,count(*) as SECOUNDCOUNT
FROM Table1
group by ACCTCCODE,ACCTDESCRIPTION