2015-12-02 70 views
0

我试图在每个日期的预留日期计数中选择不同的预留日期。我需要将reservation date表中的许可证密钥与LicenseKeyTB进行比较。T-SQL:选择具有不同值的多个列

这是我到目前为止有:

SELECT 
    l.LicenseKey, 
    numOfReservation 
FROM 
    RX.LicenseKeyTB l 
    JOIN (
    SELECT 
     r.LicenseKey, 
     DISTINCT r.ReservationDate, 
     COUNT(r.ReservationDate) 
     OVER (PARTITION BY r.ReservationDate ORDER BY r.LicenseKey) as numOfRes 
    FROM 
     RX.ReservationTB r 
) AS ReservatonDateCount 
    ON ReservatonDateCount.LicenseKey = l.LicenseKey; 

sql diagram

我收到以下错误:

Column 'RX.ReservationTB.LicenseKey' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

编辑----------- ---

对不起,我没有给出全貌。我想要做的是检查许可证密钥是否适用于某个日期范围。对于日期范围,我无法查看许可密钥s的总席位数。 Office 2010有一个许可证密钥,另外一个用于Office 2013.对于这两个许可证密钥,都有可用的总席位数。我无法完成所有席位的数目。例如我不能一次签出5个Office 2010和8个Office 2013许可,但我可以有4个和6个。

我需要查询产品(例如Office 2010)的许可证密钥,其中预留的总数日期范围不会超过可用于两个许可证密钥的总座位数。

如果预订日期的范围达到总座位数,我需要检查相应的许可证密钥。

complete sql diagram

打破这件事:

我需要做的第一件事是看我有多少保留对每一个许可证密钥给定的范围内。

-- number of reservations per day for a license key 
SELECT 
    l.LicenseKey, 
    l.ReservationDate, 
    COUNT(1) AS numOfReservation 
FROM RX.ReservationTB l 
WHERE l.LicenseKey = '6RCX3-H722D-8MQT6-8Y2VC-FY9FG' 
AND CONVERT(date, '20151130')<=l.ReservationDate 
AND l.ReservationDate<CONVERT(date, '20151205') 
GROUP BY l.LicenseKey, l.ReservationDate 
ORDER BY l.LicenseKey, l.ReservationDate 

- 我不需要在给定日期范围内可用的产品许可证密钥列表。

....

这是我到目前为止有:

​​3210

我收到此错误信息:

Msg 245, Level 16, State 1, Line 1 
Conversion failed when converting the nvarchar value '6RCX3-H722D-8MQT6-8Y2VC-FY9FG' to data type int. 
+1

'DISTINCT'只适用于**整行** - 您无法获得“不同”列值。语法是'SELECT DISTINCT(列列表)'('DISTINCT'关键字不能位于列列表的中间) –

+0

您能提供样本数据和期望的结果吗?除了错误使用'distinct'之外,您发布的错误是因为在使用'count'时''partition''中的'order by'不能使用 - 无法用count来排序... – sgeddes

+0

'DISTINCT'不是每列限定符,它是'SELECT'的修饰符。你要么'选择DISTINCT'或者你只是'SELECT' [不一定是独特的]。 –

回答

1

不是真的知道你正试图在这里做但也许它是这样简单?

SELECT r.LicenseKey 
    , r.ReservationDate 
    , COUNT(r.ReservationDate) as numOfRes 
FROM RX.ReservationTB r 
group by r.LicenseKey 
    , r.ReservationDate 
0

我觉得你只是想count(distinct)

SELECT r.LicenseKey, 
     COUNT(DISTINCT r.ReserationDate) as numOfReservation 
FROM RX.ReservationTB l 
GROUP BY r.LicenseKey; 

注意,因为LicenseKey是在保留表和似乎是LicenseTB的外键引用的连接是没有必要的。

+0

嗯。我会买“连接是没有必要的,因为'ReservationTB.LicenseKey'是一个引用许可证密钥表的外键”。但是,如果不是用于FK关系,那么联接将用于过滤掉许可证密钥表中不存在保留许可证密钥的行。当然,如果'LicenseKey'不在保留表中,给定的连接根本就不可能。 –

+0

@JohnBollinger。 。 。这是值得明确的,所以我做到了。 –

0

于你正试图在这里做了一些问题,但如果我留在2列,你在你的例子都选择我得到:

SELECT 
    l.LicenseKey, 
    COUNT(1) AS numOfReservation, 
    COUNT(DISTINCT l.ReservationDate) AS DaysLicenseUsed 
FROM RX.ReservationTB l 
GROUP BY l.LicenseKey 
ORDER BY l.LicenseKey 

如果您想获得每天的预订数量对于每个许可证,它将是:

SELECT 
    l.LicenseKey, 
    l.ReservationDate, 
    COUNT(1) AS numOfReservation, 
FROM RX.ReservationTB l 
GROUP BY l.LicenseKey, l.ReservationDate 
ORDER BY l.LicenseKey, l.ReservationDate 
相关问题