有没有办法使用SQL?

时间:2019-02-19 07:56:06

标签: sql standard-sql

我的数据格式如下:

c_time,             c_id
-------------------------
2009-01-01 12:30,   123
2009-01-01 12:31,   125
2009-01-01 12:32,   123

2009-01-02 12:31,   124
2009-01-02 12:32,   123
2009-01-02 12:33,   124

id对应于文本中的值。

  1. 如何编写查询以计算每个日期的出现次数?

  2. 如何将ID替换为对应的文本(相当于excel vlookup)?

我试图编写查询,并且想看看其他人会怎么做。

3 个答案:

答案 0 :(得分:1)

select date, count(distinct id)
from tbl
group by cast(date as date) --this forces to remove the time

答案 1 :(得分:0)

MySQL查询 select count(id),date from <your_table_name> group by date

答案 2 :(得分:0)

使用SSMS作为DBMS。

您还可以利用COUNT()OVER()common table expession和DISTINCT的优势。

--Creating the table to hold your values 
CREATE TABLE #tmpTable (
[date] DATE,
[time] TIME,
[id] BIGINT
)
-- Inserting values
INSERT INTO #tmpTable
VALUES 
('2009-01-01', '12:30', 123),
('2009-01-01', '12:31', 125 ),
('2009-01-01', '12:32', 123 ),
('2009-01-02', '12:31', 124 ),
('2009-01-02', '12:32', 123 ),  
('2009-01-02', '12:33', 124 )

-- Common table expression
WITH CTE 
AS 
(SELECT [date], [time], [id], COUNT([date]) OVER(Partition by [date],[id] order by 
[id]) AS rn FROM #tmpTable
)

SELECT DISTINCT [date], [id], [rn] 
FROM CTE 
ORDER BY id